【问题标题】:Uncaught (in promise) SyntaxError: Unexpected token ' in fetch functionUncaught (in promise) SyntaxError: Unexpected token ' in fetch 函数
【发布时间】:2016-03-07 19:23:03
【问题描述】:

我有几个 JSON 文件的结构是这样的(我们称之为 info.json):

{
  'data': {
    'title': 'Job',
    'company': 'Company',
    'past': [
      'fulltime': [
        'Former Company'
      ],
      'intern': [
        'Women & IT',
        'Priority 5'
      ]
    ],
    'hobbies': [
      'playing guitar',
      'singing karaoke',
      'playing Minecraft',
    ]
  }
}

在一个单独的 JavaScript 文件中,我有一个如下所示的函数:

function getJSONInfo() {
  fetch('info.json').then(function(response) {
    return response.json();
  }).then(function(j) {
    console.log(j);
  });
}

当我运行getJSONInfo() 时,我不断收到此错误:

Uncaught (in promise) SyntaxError: Unexpected token '

我错过了什么?我在任何地方都没有流浪的',所以我不确定出了什么问题。

【问题讨论】:

  • 我也遇到了同样的问题,但我的响应来自 .NET OAuth 代码,直到最近它才为我工作。你还记得是什么问题吗?
  • @Tom 因为我用了单引号而不是双引号,所以用单引号是无效的 JSON!

标签: javascript json fetch-api


【解决方案1】:

您需要为有效的 json 属性添加双引号。

您可以使用 json 验证器,例如 http://jsonlint.com/ 来检查您的语法是否正确。

另外,正如 shayanypn 指出的,“过去”应该是一个对象,而不是一个数组。您正在尝试将“过去”定义为对象文字,但使用方括号来表示数组。

【讨论】:

    【解决方案2】:

    你完全无效

    1- 你应该使用双引号

    2- 对象属性语法错误

    "past": [
        "fulltime": [
            "Former Company"
        ],
        "intern": [
            "Women & IT",
            "Priority 5"
        ]
    ],
    

    它应该睡觉

    "past": {
        "fulltime": [
            "Former Company"
        ],
        "intern": [
            "Women & IT",
            "Priority 5"
        ]
    },
    

    你的有效 json 是

    {
        "data": {
            "title": "Job",
            "company": "Company",
            "past": {
                "fulltime": [
                    "Former Company"
                ],
                "intern": [
                    "Women & IT",
                    "Priority 5"
                ]
            },
            "hobbies": [
                "playing guitar",
                "singing karaoke",
                "playing Minecraft"
            ]
        }
    }
    

    【讨论】:

      猜你喜欢
      • 2017-12-15
      • 1970-01-01
      • 2021-03-02
      • 2020-03-26
      • 2020-09-04
      • 1970-01-01
      • 2018-01-07
      • 2021-08-09
      • 1970-01-01
      相关资源
      最近更新 更多