如何通过字符串获取json值?

时间:2022-05-27 20:58:41

I receive the following string from the server response:

我从服务器响应中收到以下字符串:

var jsonData = '[{"firstName":"Bill","lastName":"Gates"},{"firstName":"George","lastName":"Bush"},{"firstName":"Thomas","lastName":"Carter"}]';

I see some jquery plugins can predefine the keys they want

我看到一些jquery插件可以预定义他们想要的密钥

like: index:"firstName", and they get a ul like

喜欢:index:“firstName”,他们得到一个ul之类的

<li>Bill</li>
<li>George</li>
<li>Thomas</li>

If index:"lastName", they get a ul like

如果索引:“lastName”,他们会得到一个ul

<li>Gates</li>
<li>Bush</li>
<li>Carter</li>

The only way I know how to parse a json format string is:

我知道如何解析json格式字符串的唯一方法是:

var object = JSON.parse(jsonData);
var firstName = object[i].firstName;
var lastName= object[i].lastName;

The plugin pass the index like a parameter

插件像参数一样传递索​​引

function f(index) {
    return object[i].index;
}

How can they achieve this?

他们怎么能实现这个目标?

Thanks for helping!

谢谢你的帮助!

1 个解决方案

#1


0  

You can access object properties with square brackets. JS objects work like arrays in this regard.

您可以使用方括号访问对象属性。在这方面,JS对象就像数组一样工作。

var objects = JSON.parse(jsonData),
    key = "firstName";

objects.forEach(function (obj) {
    var value = obj[key];
    // ...
});

#1


0  

You can access object properties with square brackets. JS objects work like arrays in this regard.

您可以使用方括号访问对象属性。在这方面,JS对象就像数组一样工作。

var objects = JSON.parse(jsonData),
    key = "firstName";

objects.forEach(function (obj) {
    var value = obj[key];
    // ...
});