且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在Nodejs中解析嵌套的JSON

更新时间:2023-01-12 10:50:27

您无法通过索引访问命名对象属性。您可以使用 obj [Object.keys(obj)[0]]

You just can't access named object property by index. You can use obj[Object.keys(obj)[0]]

编辑:

正如@smarx在评论中解释的那样,由于 Object.keys,此答案不适合按索引直接访问特定属性是无序的,所以它仅适用于需要循环对象的键/值的情况。

As @smarx explained in the comments, this answer is not suitable for direct access to the specific property by index due to Object.keys is unordered, so it is only for cases, when you need to loop keys/values of object.

示例:

var string = '{"key1": "value", "key2": "value1", "Key3": {"key31":"value 31"}}';
var obj = JSON.parse(string);
var keysArray = Object.keys(obj);
for (var i = 0; i < keysArray.length; i++) {
   var key = keysArray[i]; // here is "name" of object property
   var value = obj[key]; // here get value "by name" as it expected with objects
   console.log(key, value);
}
// output:
// key1 value
// key2 value1
// Key3 { key31: 'value 31' }