将JSON转换为数组Javascript
我目前正在接收一个JSON对象从我的应用程序的服务器端,结果就是这样
{"tags":"[{value: 2,label: 'Dubstep'},{value: 3,label: 'BoysIIMen'},{value: 4,label:'Sylenth1'}]"}
但是我不需要结果中的“标签”和双引号。
所以我想要的是该JSON对象的数组表示
因此,我将如何转换它
{"tags":"[{value: 2,label: 'Dubstep'},{value: 3,label: 'BoysIIMen'},{value: 4,label:'Sylenth1'}]"}
对此
[{value: 2,label: 'Dubstep'},{value: 3,label: 'BoysIIMen'},{value: 4,label:'Sylenth1'}]
这是创建数组的循环
String k = "["; List tg = audioTaggingService.findTagsByName(q); for(int i = 0; i<audioTaggingService.findTagsByName(q).size();i++){ Tag t = tg.get(i); if(i == (tg.size() - 1)){ k+="{value: "+t.getId()+",label:'"+t.getName()+"'}"; }else{ k+="{value: "+t.getId()+",label:'"+t.getName()+"'}"; } } k+="]";
上面代码的结果就是这个
[{value: 2,label: 'Dubstep'},{value: 3,label: 'BoysIIMen'},{value: 4,label:'Sylenth1'}]
假设您在一个名为response
的javascript对象中获得了服务器端响应,您可以使用$.parseJSON
函数解析tags
字符串属性。 但首先,您需要修复服务器端代码,以便为tags属性返回有效的JSON字符串(在JSON属性名称中必须用引号括起来):
// This came from the server var response = {"tags":"[{\"value\": 2,\"label\": \"Dubstep\"},{\"value\": 3,\"label\": \"BoysIIMen\"},{\"value\": 4,\"label\":\"Sylenth1\"}]"}; // Now you could parse the tags string property into a corresponding // javascript array: var tags = $.parseJSON(response.tags); // and at this stage the tags object will contain the desired array // and you could access individual elements from it: alert(tags[0].label);
如果由于某种原因您无法修改服务器端脚本以在tags
属性中提供有效的JSON,您仍然可以使用eval
而不是$.parseJSON
:
var tags = eval(response.tags);
这不是推荐的方法,通常你应该避免使用eval
因为它会执行任意的javascript。
initSelection: function (element, callback) { var data = $(element).val(); callback($.parseJSON(data)); }