简体   繁体   中英

Extract the JSON array inside the JSON string

I would like to extract the JSON array inside the JSON string. But I am not able to figure out how to get it working. Please refer the code below:

/* 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);
    });

Edit 1: Sorry guys, there was a small typo..Since, I simplified the code from my original code. Please see the refined one ..sorry for the trouble.

Thanks!

you are having error in your string check this out

 var all_barcodes = '{"VAM12345":{"colour":"red","size":"32"},"VAM456789":{"color":"red","size":"42"}}';

CHECK THIS CODE

    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);
    });

I see 2 errors with your JSON. That's why it fails to parse

  • "size","32" should be "size":"32"
  • "size","42" should be "size":"42"

Next time try http://jsonlint.org

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM