使用 JavaScript 对象表示法访问 json 值

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/7202398/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-25 23:17:01  来源:igfitidea点击:

Access json value using JavaScript object notation

javascriptjson

提问by tnt-rox

I am unable to access a json value

我无法访问 json 值

{"phone": [
{
    "@attributes": {
        "type": "cell",
        "ext": ""
    }
}, "(123) 456 7890", {
    "@attributes": {
        "type": "work",
        "ext": ""
    }
}
]}

using the following JavaScript: psudo

使用以下 JavaScript: psudo

for each phone line ...

console.log(["@attributes"].type);
console.log(this); 
console.log(["@attributes"].ext);

... end for

I expected the following output:

我期望以下输出:

cell
work (123) 456 7890

回答by diEcho

actually your json structure is not perfect, so here is the solution for your desired output

实际上你的json结构并不完美,所以这里是你想要的输出的解决方案

var json = {"phone": [
{
    "@attributes": {
        "type": "cell",
        "ext": ""
    }
}, "(123) 456 7890", {
    "@attributes": {
        "type": "work",
        "ext": ""
    }
}
]};
 console.log(json['phone'][0]['@attributes'].type);
 console.log('<br/>'+json['phone'][1]);
 console.log('<br/>'+json['phone'][2]['@attributes'].type);

DEMO

演示

回答by Adeel

since phoneis an array, try this,

因为phone是一个数组,试试这个,

   for(var i=0;i<phone.length;i++)
     console.log(phone[i].["@attributes"].type);

Also surround your response with {, as it is currently an invalid json.

还要用 包围您的响应{,因为它目前是无效的 json。

回答by Dave Mackintosh

I'm pretty sure you can't start any object, associative array key or well anything with a non-alphanumerical character.

我很确定你不能启动任何对象、关联数组键或任何带有非字母数字字符的东西。

Also you have 3 calls to console and only two lines of expected output? What does console.log(this) output?

您也有 3 次调用控制台并且只有两行预期输出?console.log(this) 输出什么?

回答by muffir

I think your phonearray is quite messy because you have:

我认为你的phone数组很乱,因为你有:

phone[0] === {'@attributes':...}
phone[1] === '(123) 456 7890'
phone[2] === {'@attributes':...}

Is that what you realy wanted to have there?

那是你真正想要的吗?