【问题标题】:Getting a particular attribute from a JSON data [duplicate]从 JSON 数据中获取特定属性 [重复]
【发布时间】:2019-05-12 17:27:23
【问题描述】:

我的 api 调用有这个结果 JSON 数据,但是当我尝试访问属性“69106658_5”中的数据时,我无法访问,我收到“错误:未捕获的语法错误:无效或意外令牌”。我有一份我在下面的在线编辑上运行的副本。我猜是因为该属性包含下划线。

let results=
    {
    "links": {
        "data": {
            "self": {
                "body": "",
                "content_type": "",
                "href": "/api/v2/nodes/69107289/categories",
                "method": "GET",
                "name": ""
            }
        }
    },
    "results": [
        {
            "data": {
                "categories": {
                    "58652374_10": [
                        "16",
                        "16.0.1",
                        "16.2",
                        "16.2.4"
                    ],
                    "58652374_11": [
                        "English"
                    ],
                    "58652374_12": [
                        "Windows"
                    ],
                    "58652374_13": "2018-11-20T00:00:00",
                    "58652374_2": "Published",
                    "58652374_3": "19",
                    "58652374_4": "Video",
                    "58652374_5": "65",
                    "58652374_6": "How To",
                    "58652374_7": [
                        "basic"
                    ],
                    "58652374_8": "237",
                    "58652374_9": "Content Server"
                }
            }
        },
        {
            "data": {
                "categories": {
                    "69106658_2": "You Tube",
                    "69106658_3": [
                        "End User"
                    ],
                    "69106658_4": [
                        "69106508:7"
                    ],
                    "69106658_5": "https://img.youtube.com/vi/j-aOeCpRvEs/hqdefault.jpg",
                    "69106658_6": false,
                    "69106658_7": "Engineering",
                    "69106658_8": null
                }
            }
        }
    ]
    }

    var lookInto = results.results;

    for( let key in lookInto ) {
     var selectData = lookInto[key].data.categories;
     console.log(selectData);
    }

    console.log( selectData.69106658_5 )

【问题讨论】:

  • 尝试:console.log(selectData['69106658_5'])
  • @CupofJava 非常感谢
  • @SebastianFelixSchwarz 谢谢!

标签: javascript arrays json postman


【解决方案1】:

下划线应该不会造成任何问题。 如果你想访问属性“69106658_5”,你应该这样做:

results.results[1].data.categories["69106658_5"]

【讨论】:

  • 非常感谢!
【解决方案2】:

以非字母(以及一些符号如_)开头的属性字段,您必须使用括号表示法才能访问。

试试selectData['69106658_5'],而不是selectData.69106658_5

【讨论】:

  • 非常感谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-03-10
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-03-30
相关资源
最近更新 更多