开发者

jquery parsing json

This is the JSON output that I currently have:

[{"pk": 1, "model": "system.employees", 
"fields": {"chi_name": "N/A", "eng_name": "Eli"}}]

I want the output to be

[{"label": "Eli", "value": "1"}]开发者_运维技巧

how can I take the values of pk and eng_name from the JSON data and output it like above?


You can use jQuery.map:

var data = [{"pk": 1, "model": "system.employees", 
    "fields": {"chi_name": "N/A", "eng_name": "Eli"}}];

var new = $.map(data, function(index, item) {
        return { label: item.fields.eng_name, value: item.pk };
    });


var result = [{"pk": 1, "model": "system.employees", "fields": {"chi_name": "N/A", "eng_name": "Eli"}}]
var output = [{ "label" : result[0].fields.eng_name, "value": result[0].pk}]


//assuming your source obj is called 'source'
var num = source[0].pk;
var eng_name = source[0].fields.eng_name;

...then you can do whatever with them, like

var output = [];
output.push({"label":eng_name, "value":num});

Good luck!


Try -

var h = JSON.parse('[{"pk": 1, "model": "system.employees", "fields": {"chi_name": "N/A", "eng_name": "Eli"}}]');
var a = [];
a.push({"label": h[0].fields.eng_name, "value": h[0].pk+''})
alert(JSON.stringify(a))

NB You'll need to import this code - https://github.com/douglascrockford/JSON-js/blob/master/json2.js if your browser doesn't support JSON.parse and JSON.stringify

Demo - http://jsfiddle.net/ipr101/uwZVW/

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜