简体   繁体   English

Json提取和使用数据(node.js)

[英]Json extract and use data (node.js)

How can I access this data? 我该如何访问这些数据?

Here is my Json: 这是我的Json:

 {
  "6a768d67-82fb-4dd9-9433-d83dbd2f1b78": {
    "name": "Bahut",
    "11": {
      "timestamp": 1380044486000,
      "value": "false"
    }
  },
  "4f4a65e4-c41b-4038-8f62-76fe69fedf60": {
    "name": "Vit",
    "11": {
      "timestamp": 1380109392000,
      "value": "false"
    }
  },
  "a12d22cc-240e-44d6-bc58-fe17dbb2711c": {
    "name": "Cuis",
    "11": {
      "timestamp": 1379883923000,
      "value": "false"
    }
  }
}

I'm trying to read and extract for each entries the id (xxxxxxxx-xxxx-...-xxxxxxxxx) and the "name" to put then in an array. 我正在尝试读取并提取每个条目的id(xxxxxxxx-xxxx -...- xxxxxxxxx)和“name”以将其放入数组中。

But I didn't manage to do. 但我没办法做到。

trying : 试 :

var nameid = json.'XXXXX-....-XXXX'.name;

or replace '-' by '' 或者用''代替' - '

var nameid = json.XXXXXXXXX.name;

didn't work too. 也没用。

You need to use array-style access to get the subobject associated with the id key: 您需要使用数组样式访问来获取与id键关联的子对象:

var nameid = json["a12d22cc-240e-44d6-bc58-fe17dbb2711c"].name; // or ["name"]
// nameid => "Cuis"

This is because hyphens are not a valid character for dot-style access (can't use them in variable names in JavaScript). 这是因为连字符不是点样式访问的有效字符(不能在JavaScript中的变量名中使用它们)。

In order to extract all of the you will need to loop through the object, and add them to an array, like so: 为了提取所有你需要循环遍历对象,并将它们添加到数组,如下所示:

var arr = [];
for (var id in json) {
    arr.push(json[id]["name"]);
}

Which will give you an array of all the names in that JSON object. 这将为您提供该JSON对象中所有名称的数组。

If you want to loop through the data, use a for in loop: 如果要循环访问数据,请使用for in循环:

for (var key in obj) { //obj is your data variable
    console.log(key); //xxxx-x-xx-x-x-xxxx
    console.log(obj[key].name); //the name for each
}

You could use Object.keys to get an array of properties. 您可以使用Object.keys来获取属性数组。

var js = JSON.parse(json);
var props = Object.keys(js);

var result = props.map(function(prop) {
  return {
    id: prop,
    name: js[prop].name;
  };
});

The final result is an array of objects with 2 properties: id , name 最终结果是具有2个属性的对象数组: idname

Access the JSON like you would an array, eg: 像访问数组一样访问JSON,例如:

data["a12d22cc-240e-44d6-bc58-fe17dbb2711c"].name

jsfiddle 的jsfiddle

not a common way of looping, but in this case you could loop over the json object 不是常见的循环方式,但在这种情况下,您可以遍历json对象

for (var prop in json){
     print("prop",json[prop].name);
}

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

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