简体   繁体   中英

AngularJS: Unable to parse a list of JSON

The following is the JSON I'm trying to parse:

{[{"name":"Technology"},{"name":"Engineering"},{"name":"Business"}]}

I'm getting the error below:

Unexpected token [ in JSON at position 1
    at JSON.parse (<anonymous>)
    at fromJson

I'm getting the data from a service and saving it into the controller scope using the following:

vm = this;
vm.sectorList = response.data;

And my HTML:

<div ng-repeat="sector in ctrl.sectorList">
    {{sector.name}}
</div>

The JSON is invalid, hence the error you're getting. You're missing a key to go with the JSON array value. This for instance (key "anything" added) will work:

{"anything": [{"name":"Technology"},{"name":"Engineering"},{"name":"Business"}]}

If the response is an array it should not be enclosed in curly brackets {} . This would be valid JSON:

[{"name":"Technology"}, {"name":"Engineering"}, {"name":"Business"}]

You are also trying to use JSON.parse on an object, when it takes a string as input parameter. If you want to make an object into a JSON string you should use JSON.stringify .

Your JSON is invalid you can validate your JSON Here

It should be:

[{
    "name": "Technology"
}, {
    "name": "Engineering"
}, {
    "name": "Business"
}]

Your key is missing.

{"YourKEY": [{"name":"Technology"},{"name":"Engineering"},{"name":"Business"}]}

You cannot access object of arrays without key.

you need to assign the array to property of the object. can't assign array just inside of the object without property

{  
   "items":[  
      {  
         "name":"Technology"
      },
      {  
         "name":"Engineering"
      },
      {  
         "name":"Business"
      }
   ]
}

in the ng-repeat it should change as following

<div ng-repeat="sector in ctrl.sectorList.items">
    {{sector.name}}
</div>

您应该在JSON中的[]之前删除花括号:

[{"name":"Technology"},{"name":"Engineering"},{"name":"Business"}]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM