简体   繁体   English

解析 JSON 中的对象,并检索数据

[英]Parse objects in JSON, and retrieve data

So I have a variable name "userList".所以我有一个变量名“userList”。

This variable is a JSON containing a few objects, depending on the amount of users online...这个变量是一个包含几个对象的 JSON,具体取决于在线用户的数量...

Here is the JSON/variable stringifed: (Contains two users.)这是 JSON/变量 stringifed:(包含两个用户。)

{
  "User1": {
    "ident": "guest#1",
    "username": "Guest1",
    "posx": 2,
    "posy": 10,
    "lineWidth": "1",
    "lineColor": "00baff"
  },
  "User2": {
    "ident": "guest#2",
    "username": "Guest 2",
    "posx": 1,
    "posy": 5,
    "lineWidth": "1",
    "lineColor": "000000"
  }
}

How could I log every objects "username" value?如何记录每个对象的“用户名”值? Here's my script:这是我的脚本:

if (obj.msg === "/log") { //If EventSource's obj.msg ='s ...
  var list = JSON.stringify(userList) //String the variable.
  console.log(list) // Log the objects.
} else {
  console.log("Event msg is not /log ")
}

I've tried doing this:我试过这样做:

console.log(list.username)

You can loop through the object's keys and access the username fields like this:您可以遍历对象的键并访问用户名字段,如下所示:

 var list = { "8micxp7q5w5tfsrkkw9iys7l2ead7tls": { "ident": "8micxp7q5w5tfsrkkw9iys7l2ead7tls", "username": "Antidote", "posx": 1002, "posy": 125, "lineWidth": "1", "lineColor": "00baff", "ignore": false, "status": "w" }, "1fjw6u6ok8q6jrqcnr47yymbaida2iwp": { "ident": "1fjw6u6ok8q6jrqcnr47yymbaida2iwp", "username": "from Lehi, United States", "posx": 989, "posy": 124, "lineWidth": "1", "lineColor": "000000", "ignore": false, "status": "w" } } for (item in list) { console.log(list[item]['username']) }

You have a map of two objects, you can only access them using their key.您有两个对象的映射,您只能使用它们的密钥访问它们。 Also, JSON.stringify returns a string.此外, JSON.stringify返回一个字符串。 To parse a string to from a JSON object, use JSON.parse.要将字符串解析为 JSON 对象,请使用 JSON.parse。

if (obj.msg === "/log") { //If EventSource's obj.msg ='s ...
  var list = JSON.parse(JSON.stringify(userList)) // this is not needed your userList is already parsed
  
  // First Approach es5
  for(var key in list){
    console.log(list[key].username); // here is how u can access your name
  }

  // Second Approach es6
  for (const item of list){
    console.log(item.username);
  }
} else {
  console.log("Event msg is not /log ")
}

Your console.log() statement doesn't reference the key despite referencing the value, so it would make more sense to do:尽管引用了值,但您的console.log()语句并未引用键,因此这样做更有意义:

console.log(list["8micxp7q5w5tfsrkkw9iys7l2ead7tls"].username);

If you aim to get the username values of the keys of the objects manually/individually rather than iterating through the username instances in the object's keys, you could also use the JSON.parse() method as follows.如果您的目标是手动/单独获取对象键的username值,而不是遍历对象键中的username实例,您还可以使用 JSON.parse() 方法,如下所示。 Make sure your JSON list is a string:确保您的 JSON 列表是一个字符串:

var list = '{ "pmicxp7q5w5tfsrkkw9iys7l2ead7tls": { "ident": "8micxp7q5w5tfsrkkw9iys7l2ead7tls", 
   "username": "Antidote", "posx": 1002, "posy": 125, "lineWidth": "1", "lineColor": "00baff", 
   "ignore": false, "status": "w"}, "1fjw6u6ok8q6jrqcnr47yymbaida2iwp": { "ident": 
   "1fjw6u6ok8q6jrqcnr47yymbaida2iwp", "username": "from Lehi, United States", "posx": 989, 
   "posy": 124, "lineWidth": "1", "lineColor": "000000", "ignore": false, "status": "w"}}';

var obj = JSON.parse(list);
var username1 = obj["8micxp7q5w5tfsrkkw9iys7l2ead7tls"].username;   // or obj.8micxp7q5w5tfsrkkw9iys7l2ead7tls.username
var username2 = obj["1fjw6u6ok8q6jrqcnr47yymbaida2iwp"].username;   // or obj.1fjw6u6ok8q6jrqcnr47yymbaida2iwp.username

To show all the users usernames at once, you can use Object.values(userList) to get an array of the objects inside userList object then use forEach method to loop through that new array :要一次显示所有用户的用户名,您可以使用Object.values(userList)获取userList对象内的对象数组,然后使用forEach方法循环遍历该新array

 const userList = { "8micxp7q5w5tfsrkkw9iys7l2ead7tls": { "ident": "8micxp7q5w5tfsrkkw9iys7l2ead7tls", "username": "Antidote", "posx": 1002, "posy": 125, "lineWidth": "1", "lineColor": "00baff", "ignore": false, "status": "w" }, "1fjw6u6ok8q6jrqcnr47yymbaida2iwp": { "ident": "1fjw6u6ok8q6jrqcnr47yymbaida2iwp", "username": "from Lehi, United States", "posx": 989, "posy": 124, "lineWidth": "1", "lineColor": "000000", "ignore": false, "status": "w" } } Object.values(userList).forEach(i => console.log(i.username));

But if you need to get the username from a certain object in userList , you'll need to access that object using it name (key) :但是,如果您需要从userList的某个对象获取用户名,则需要使用它的 name (key) 访问该对象:

 const userList = { "8micxp7q5w5tfsrkkw9iys7l2ead7tls": { "ident": "8micxp7q5w5tfsrkkw9iys7l2ead7tls", "username": "Antidote", "posx": 1002, "posy": 125, "lineWidth": "1", "lineColor": "00baff", "ignore": false, "status": "w" }, "1fjw6u6ok8q6jrqcnr47yymbaida2iwp": { "ident": "1fjw6u6ok8q6jrqcnr47yymbaida2iwp", "username": "from Lehi, United States", "posx": 989, "posy": 124, "lineWidth": "1", "lineColor": "000000", "ignore": false, "status": "w" } } console.log(userList['8micxp7q5w5tfsrkkw9iys7l2ead7tls'].username); /** output: Antidote **/ console.log(userList['1fjw6u6ok8q6jrqcnr47yymbaida2iwp'].username); /** output: from Lehi, United States **/

You know that username is not an attribute of the userList object, so you need to iterate over the Object in order to access each user object:您知道username不是userList对象的属性,因此您需要遍历Object以访问每个用户对象:

for (var ident in userList) {
    if (userList.hasOwnProperty(ident)) {
        console.log(userList[ident].username);
    }
}

Also, are you trying access attributes of the String list ?另外,您是否尝试访问字符串list属性? If you want to access the attributes programmatically you should keep the Object as userList , because once you call JSON.stringify(userList) , you'll get a pretty useless String representation of the Object .如果您想以编程方式访问属性,您应该将Object保留为userList ,因为一旦您调用JSON.stringify(userList) ,您将获得Object一个非常无用的String表示。

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

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