JSON解析错误意外令牌

时间:2018-08-12 19:20:54

标签: javascript arrays json node.js parsing

JSON数据采用这种格式。

[{
    "_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"
}]

我正试图让朋友“ fid”和“ fname”,但这样做很难。 我正在做这样的事情。

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

最初,数据位于“数据”变量中。通过这样做console.log((actual.friends));,我得到了以下结果。

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

无法进一步提取数据。谢谢

1 个答案:

答案 0 :(得分:0)

通过遍历actual.friends,可以获得fidfname的值。

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);
});

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);
  });
});