Uffo
Uffo

Reputation: 10056

Is there a way to parse this json using jquery

Is there a way to parse this using jquery?

{"post_title":["car1","car2","car3"],"guid":["http:\/\/car1\/body\/fiat\/","http:\/\/car2\/body\/fiat\/","http:\/\/car3\/body\/fiat\/"]}

 $.getJSON($theUrl, function(data){
        var myData = [];
        $.each(data, function(i, item) {
          console.log(item[0]);
          myData.push("<li><a href="+item+">" + item+ "</a></li>");
        });

PHP CODE:

$s = array();
while (have_posts()) : the_post();
  $s['post_title'][] = get_the_title();
  $s['guid'][] = get_permalink();
endwhile; 
echo json_encode($s);

Can someone help me please!

Upvotes: 0

Views: 187

Answers (6)

one.beat.consumer
one.beat.consumer

Reputation: 9504

If you are trying to parse the JSON string on the client-side, jQuery will work and the syntax would be:

var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );

API jQuery - jQuery.parseJSON()

If you are trying to parse it on the server-side the syntax and tools would depend on what JSON library you are using. I am not familiar with PHP so I do not know what is available there.

Side note - make sure your JSON is properly formed before you worry about parsing.

Upvotes: 0

Corbin
Corbin

Reputation: 33457

I think you should probably be building your data differently.

$s = array();
while (have_posts()) : the_post();
  $s['post_title'][] = get_the_title();
  $s['guid'][] = get_permalink();
endwhile; 
echo json_encode($s);

Should likely be:

$s = array();
while (have_posts()) : the_post();
    $s[] = array(
        'post_title' => get_the_title(),
        'guid' => get_permalink(),
    );    
endwhile; 
echo json_encode($s);

Then your JS would look something like:

$.getJSON($theUrl, function(data){
    $.each(data, function(i, item) {
        //item.post_title
        //item.guid
    });
});

Upvotes: 2

Zoltan Toth
Zoltan Toth

Reputation: 47677

parseJSON() - http://jsfiddle.net/VHpLp/

Upvotes: 1

isNaN1247
isNaN1247

Reputation: 18099

jQuery does have jQuery.parseJSON

Or you could just use 'JSON.parse()' with json2.js as a fallback for browsers that don't natively support this.

Upvotes: 1

swatkins
swatkins

Reputation: 13640

You could try parseJSON:

jQuery.parseJSON();

Upvotes: 1

JP Richardson
JP Richardson

Reputation: 39415

Ya, to parse JSON on the client/browser, use:

 var jsonObj = JSON.parse(yourJsonString);

Upvotes: 0

Related Questions