首页 > 解决方案 > 访问 JSON 中的特定键?

问题描述

我正在尝试使用 NodeJS 访问此 JSON 对象的“标题”部分(键?)。我可以返回整个对象,但是每次我尝试访问密钥时,都会返回 undefined。

[
    [
        {
            "id": 119,
            "title": "Roadhouse",
            "url": "https://funsite.com/2021/03/20/funny/",
            "date": "2021-03-20"
        }
    ],
    [
        {
            "id": 208,
            "title": "New Sites",
            "url": "https://coolsitestuff.com/notes/coolsite/",
            "date": "2021-03-17"
        }
    ],
    [
        {
            "id": 13,
            "title": "woah sites!!",
            "url": "https://now.lettuce.com/then/2021-0000/",
            "date": "2021-03-07"
        }
    ],
    [
        {
            "id": 120,
            "title": "mynewalbumn",
            "url": "https://notarealsite.com/2021/03/06/next-album/",
            "date": "2021-03-06"
        }
    ],
    [
        {
            "id": 140,
            "title": "fightingthemans",
            "url": "http://fightcats.com/2021/03/06/keyfights",
            "date": "2021-03-06"
        }
    ],
    [
        {
            "id": 14,
            "title": "biggest lettuce youll ever see",
            "url": "https://morelettuce.com/then/biggestlettuceleaf/",
            "date": "2021-02-28"
        }
    ]
]

节点JS

const fs = require('fs')


fs.readFile('./data/links.json', 'utf8', (err, fsToString) => {
    let data = JSON.parse(fsToString);
    console.log(data.map(link => link[link.url]))
})

我已经尝试过以这种方式进行循环和索引,但我无法从中得到任何东西。

标签: javascriptnode.jsjson

解决方案


你有 2 个数组,要么遍历它们要么使用index

let data =[
    [
        {
            "id": 119,
            "title": "Roadhouse",
            "url": "https://funsite.com/2021/03/20/funny/",
            "date": "2021-03-20"
        }
    ],
    [
        {
            "id": 208,
            "title": "New Sites",
            "url": "https://coolsitestuff.com/notes/coolsite/",
            "date": "2021-03-17"
        }
    ]
]


data.map(link=> console.log(link[0].url))


推荐阅读