我想在JSON字符串中提取JSON数组。但我无法弄清楚如何让它发挥作用。请参考以下代码:
/* I would like to get this working */
var all_barcodes = '{"VAM12345":{"colour":"red","size":"32"},"VAM456789":{"color":"red","size":"42"}}';
var print = $.parseJSON(all_barcodes); // this fails and hence the below loop won't run
$.each( print, function( key, value ) {
var color = value['color'];
var design = value['size'];
alert(color); alert(size)
});
/* This works well */
var test_string = '{"VAM12345":"test1","VAM456789":"test2"}';
var print_test = $.parseJSON(test_string);
$.each( print_test, function( key, value ) {
alert(key);
alert(value);
});
编辑1:对不起家伙,有一个小错字。因为,我简化了原始代码中的代码。请看看精致的..解决问题。
谢谢!
答案 0 :(得分:1)
你的字符串中有错误检查
var all_barcodes = '{"VAM12345":{"colour":"red","size":"32"},"VAM456789":{"color":"red","size":"42"}}';
检查此代码
var all_barcodes = '{"VAM12345":{"colour":"red","size":"32"},"VAM456789":{"color":"red","size":"42"}}';
var print = $.parseJSON(all_barcodes); // this fails and hence the below loop won't run
$.each( print, function( key, value ) {
var color = value['color'];
var design = value['size'];
alert(color);
alert(design);// variable name is design not size
});
/* This works well */
var test_string = '{"VAM12345":"test1","VAM456789":"test2"}';
var print_test = $.parseJSON(test_string);
$.each( print_test, function( key, value ) {
alert(key);
alert(value);
});
答案 1 :(得分:0)
我看到你的JSON有2个错误。这就是为什么它无法解析
"size","32"
应为"size":"32"
"size","42"
应为"size":"42"