0

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!

3
  • 1
    You have an error in the string, single quote after size... That's probably all that is wrong... Commented May 16, 2014 at 6:34
  • Edited, thanks..just a typo..no error in the original code..thanks.>! Commented May 16, 2014 at 6:35
  • @ChintanParekh hence my answer. Commented May 16, 2014 at 6:39

2 Answers 2

1

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);
    });
Sign up to request clarification or add additional context in comments.

1 Comment

My mistake, I made a mess in putting up the question. Thanks though .>! :) (Also, there is a mess in the spelling in colour due to autocorrect )
0

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.