简体   繁体   中英

JSON parse error unexpected token

JSON data is something in this format.

[{
    "_id": "5b706faf2605576fefb9ae9c",
    "index": 0,
    "guid": "46850469-5924-4966-b7d6-92125444cf98",
    "isActive": true,
    "balance": "$2,983.78",
    "friends": [{
            "fid": 0,
            "fname": "Sondra Fields"
        },
        {
            "fid": 1,
            "fname": "Sondra"
        },
        {
            "fid": 2,
            "fname": "Fields"
        }
    ],
    "greeting": "Hello,",
    "favoriteFruit": "apple"
}]

I am trying to get friends "fid" and "fname" but having the hard time doing so. I am doing something like this.

var dat = { array: data }
var actual = dat.array.reduce((p, n, index) => p.concat(n[index - 1]))

initially data is in "data" variable. by doing this console.log((actual.friends)); I got the following result.

  [ { fid: 0, fname: 'Sondra Fields' },
  { fid: 1, fname: 'Sondra' },
  { fid: 2, fname: 'Fields' } ]

Unable to further extract the data. Thank you

By Iterating over actual.friends you can get the value of fid and fname .

 data=[ { "_id": "5b706faf2605576fefb9ae9c", "index": 0, "guid": "46850469-5924-4966-b7d6-92125444cf98", "isActive": true, "balance": "$2,983.78", "friends": [ { "fid": 0, "fname": "Sondra Fields" }, { "fid": 1, "fname": "Sondra" }, { "fid": 2, "fname": "Fields" } ], "greeting": "Hello,", "favoriteFruit": "apple" } ] var dat = { array: data } var actual = dat.array.reduce((p, n, index) => p.concat(n[index - 1])) actual.friends.forEach(function(element) { console.log(element.fid,element.fname); }); 

or

data.forEach(function(ele) {
ele.friends.forEach(function(element) {
  console.log(element.fid,element.fname);
  });
});

 data=[ { "_id": "5b706faf2605576fefb9ae9c", "index": 0, "guid": "46850469-5924-4966-b7d6-92125444cf98", "isActive": true, "balance": "$2,983.78", "friends": [ { "fid": 0, "fname": "Sondra Fields" }, { "fid": 1, "fname": "Sondra" }, { "fid": 2, "fname": "Fields" } ], "greeting": "Hello,", "favoriteFruit": "apple" } ] data.forEach(function(ele) { ele.friends.forEach(function(element) { console.log(element.fid,element.fname); }); }); 

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