0

你能告诉我如何在 javascript 中读取 json 吗?

我有一个 json 字符串,如下所示

 {"person":{"First name":"Dharmalingm","Last name":"Arumugam","Address":{"door number":"123","street":"sample street","city":"sample_city"},"phone number":{"mobile":"0123","landline":"01234","skype":"01235"}}}

我想读Skype电话号码

4

3 回答 3

6

如果您从 JSON 字符串开始,请以1. 如果你已经有一个 JS 对象,那么跳到2.

  1. 解析字符串JSON.parse()用于将 JSON 字符串转换为 JS 对象。要支持没有原生 JSON 的浏览器,您可以使用Crockford 的 JSON2 库来实现它。

    var jsondata = JSON.parse('{"person":{"First name":"Dharmalingm","Last name":"Arumugam","Address":{"door number":"123","street":"sample street","city":"sample_city"},"phone number":{"mobile":"0123","landline":"01234","skype":"01235"}}}');
    
  2. 像平常一样从 JS 对象中检索值

    var skype = jsondata.person['phone number'].skype;
    

这是完整的代码和示例

var jsondata = JSON.parse('{"person":{"First name":"Dharmalingm","Last name":"Arumugam","Address":{"door number":"123","street":"sample street","city":"sample_city"},"phone number":{"mobile":"0123","landline":"01234","skype":"01235"}}}');

//normally, the dot-notation is used
//but since "phone number" is not a valid key when using dot-notation
//the bracket notation is used
var skype = jsondata.person['phone number'].skype;
于 2012-05-23T21:09:24.050 回答
5

这应该让你上路。

var o = {"person":{"First name":"Dharmalingm","Last name":"Arumugam","Address":{"door number":"123","street":"sample street","city":"sample_city"},"phone number":{"mobile":"0123","landline":"01234","skype":"01235"}}}

o["person"]["phone number"]["skype"];

/* or */

o.person["phone number"]["skype"];
于 2012-05-23T21:10:17.360 回答
0

首先需要将其解析为原生 javascript 对象,在现代浏览器中,这可以通过JSON.parse(json string here);. 现在要专门获取Skype号码,您拥有刚刚解析出的对象。假设您通过 分配它var skypeData = JSON.parse(json string here);,可以通过 访问人员的Skype号码skypeData.person['phone number'].skype。我们必须使用['phone number']而不是person.phone number.skype因为空间。

于 2012-05-23T21:13:03.933 回答