Uncaught (in promise) SyntaxError: Unexpected token ' in fetch function

旧巷老猫 提交于 2019-12-12 09:39:25

问题


I have a couple JSON files that are structured like this (let's call this info.json):

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

And in a separate JavaScript file, I have a function that looks like this:

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

And I keep getting this error when I run getJSONInfo():

Uncaught (in promise) SyntaxError: Unexpected token '

What am I missing? I don't have a stray ' anywhere so I'm not sure what's wrong.


回答1:


You need to have double quotes for your attributes for valid json.

You can use json validators such as http://jsonlint.com/ to check if your syntax is correct.

Also, as shayanypn pointed out, "past" should be an object, rather than an array. You are trying to define "past" as an object literal but are using square brackets to denote an array.




回答2:


you is invalid at all

1- you should use double quotes

2- bad syntax of object attribute

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

it should bed

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

your valid json is

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


来源:https://stackoverflow.com/questions/35852192/uncaught-in-promise-syntaxerror-unexpected-token-in-fetch-function

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!