繁体   English   中英

如何获取嵌套 JSON object (第二级和一般)的某个键的值?

[英]How to get the value of a certain key of a nested JSON object (2nd level and in general)?

我有一个嵌套的 JSON Object 称为“数据”。

console.log(Object.values(data['Meta']['Symbol']));

这给了我价值的每一个字母/字符:

Array(3) [ "S", "A", "P" ]

我想要的是整个字符串:“SAP”错误在哪里?

我尝试过的事情:

这给了我整个数组(包括“SAP”),但我只想要字符串,即值“SAP”:

console.log(Object.values(data['Meta']

这给了我一个空数组(三个元素):

console.log(Object.keys(data['Meta']['Symbol']));

我在互联网上寻找的信息并没有解决这个问题。

JSON object的结构:

{
    "Meta": {
        "Symbol": "SAP"
    }
}

首先,这不是 JSON; JSON 是一个字符串。 接下来,如果要将数组转换为字符串,请使用 array.join("");

console.log(data['Meta']['Symbol'].join(""));

如果 JSON object 是

{
    "Meta": {
       "Symbol": "SAP"
    }
}

然后你用let data = JSON.parse("MY JSON")导入它然后它就是console.log(data.Meta.Symbol)

为什么

const data = { Meta: { Symbol: 'SAP' } };

/**
 * 1. String is an object;
 * 2. Using the Objects.prototype.values method will return an array of all the values (e.g. All the characters in the String.);
 * 
 * MDN documentation
 * ------------------------------------------------------
 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_objects/Object/values
 * ------------------------------------------------------
 */
console.log(Object.values(data['Meta']['Symbol']));

Output

[ 'S', 'A', 'P' ]

如何

const data = { Meta: { Symbol: 'SAP' } };

/**
 * To retrieve the value of the string, you must access it using the dot notation or bracket notation.
 *
 * Dot notation: data.Meta.Symbol
 * Bracket notation: data['Meta']['Symbol']
 *
 * MDN documentation
 * ------------------------------------------------------
 * https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Property_accessors
 * ------------------------------------------------------
 */
console.log(data['Meta']['Symbol']);

Output

SAP

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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