0

Please view my other question here

I am trying to work out how to decode a JSON response from a PHP file.

The JSON is structured as follows:

[{
    "id": 1,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/amazon-webstore-379672",
        "price": " - "
    }
}, {
    "id": 2,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/we-need-someone-to-design-t-shirts-for-the-world-cup-2014-379671",
        "price": "\u00a3 50 "
    }
}, {
    "id": 3,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/unusual-request-for-expert-help-to-work-on-lowering-google-p-379670",
        "price": "\u00a3 50 "
    }
}, {
    "id": 4,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/1-to-2-developers-to-work-on-a-large-project-379669",
        "price": " - "
    }
}, {
    "id": 5,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/we-would-like-someone-to-design-some-world-cup-t-shirts-for-379665",
        "price": "\u00a3 50 "
    }
}, {
    "id": 6,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/graphic-design-of-3-x-sample-pages-for-a-website-379664",
        "price": "\u00a3 200 "
    }
}, {
    "id": 7,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/youtube-channel-art-379663",
        "price": "\u00a3 9 "
    }
}, {
    "id": 8,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/pr-events-organisation-source-prizes-for-charity-raffle-379661",
        "price": "\u00a3 100 "
    }
}, {
    "id": 9,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/wordpress-thesis-website-finessing-improve-main-opt-in-des-379659",
        "price": "\u00a3 40 "
    }
}, {
    "id": 10,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/i-would-like-my-logo-redesigned-updated-379651",
        "price": "\u00a3 10 "
    }
}, {
    "id": 11,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/pattern-maker-pattern-cutter-379650",
        "price": " - "
    }
}, {
    "id": 12,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/add-captcha-379652",
        "price": "\u00a3 30 "
    }
}, {
    "id": 13,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/setup-salesforce-api-so-we-can-just-pull-data-via-rest-379638",
        "price": "\u00a3 31 "
    }
}, {
    "id": 14,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/simple-map-illustration-379643",
        "price": "\u00a3 25 "
    }
}, {
    "id": 15,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/time-lapse-video-for-indoor-construction-project-12-week-p-379637",
        "price": "\u00a3 1.0k "
    }
}, {
    "id": 16,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/i-need-a-asterisk-vicidial-expert-to-help-support-us-379640",
        "price": "\u00a3 15 "
    }
}, {
    "id": 17,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/i-need-a-freelancer-to-provide-help-setting-up-cytoscape-379641",
        "price": "\u00a3 21 \/hr"
    }
}, {
    "id": 18,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/500-word-article-on-business-today-379632",
        "price": "\u00a3 12 "
    }
}, {
    "id": 19,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/web-interface-app-design-379629",
        "price": "\u00a3 20 \/hr"
    }
}, {
    "id": 20,
    "info": {
        "title": "http:\/\/www.peopleperhour.com\/job\/distribute-leaflets-in-central-birmingham-379630",
        "price": "\u00a3 7 \/hr"
    }
}]

You can view the current AJAX call on my other question (Link at top of this post).

Could anyone shed some light on how I would decode the JSON array client-side?

I'd like to have a structure like this:

<div class="item">
    <div class="title">JSON Title</div>
    <div class="price">JSON Price</div>
</div>
Community
  • 1
  • 1
MikeF
  • 485
  • 6
  • 22
  • `JSON.parse(json_string)` - https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/JSON/parse – techfoobar Dec 10 '13 at 10:37
  • 1
    It's jQuery, it should be parsed automatically. (Assuming the server isn't claiming the JSON is HTML). – Quentin Dec 10 '13 at 10:44
  • Refer to this link http://stackoverflow.com/questions/18286638/how-to-convert-json-encoded-php-array-to-an-array-in-javascript – user2936213 Dec 10 '13 at 10:54
  • possible duplicate of [How to parse JSON in JavaScript](http://stackoverflow.com/questions/4935632/how-to-parse-json-in-javascript) – Rob Baillie Dec 10 '13 at 11:07

3 Answers3

1

This is how you do it. What you need is JSON.parse()

test.php

<?php

// Ajax-Server Request Handler
if (isset($_GET['loadData'])) {
    exit(json_encode(array(
        array(
            'id' => 1,
            'info' => array('title' => 'http://www.peopleperhour.com/job/amazon-webstore-379672', 'price' => ' - ')
        ),
        array(
            'id' => 2,
            'info' => array('title' => 'http://www.peopleperhour.com/job/we-need-someone-to-design-t-shirts-for-the-world-cup-2014-379671', 'price' => '\u00a3 50 ')
        ),
        array(
            'id' => 3,
            'info' => array('title' => 'http://www.peopleperhour.com/job/unusual-request-for-expert-help-to-work-on-lowering-google-p-379670', 'price' => '\u00a3 50 ')
        )
    )));
}

?>

<!-- Ajax-Client -->
<script type="text/javascript" src="http://code.jquery.com/jquery-1.10.2.min.js"></script>
<script type="text/javascript">

// When Page Loads
$(document).ready(function()
{
    // Make Ajax Request
    $.get("test.php?loadData", function(data)
    {
        // Parse Data
        var jsonResults = JSON.parse(data);

        // Iterate Through Results
        $.each(jsonResults, function(key, value)
        {
            // Display Data
            $('.results').append(
                '<div class="item" id="'+ value.info.id +'">'+
                '<div class="title">'+ value.info.title +'</div>'+
                '<div class="price">'+ value.info.price +'</div>'+
                '</div>'
            );
        });
    });
});

</script>

<!-- HTML Page - Display Result -->
<div class="results"></div>
Latheesan
  • 23,247
  • 32
  • 107
  • 201
1

Note : from your other question, it is not clear if you always expect a json answer, or if you can receive either of json, html, or xml.

If you always expect json :

$.ajax({ url: ..., data: ...,
    dataType: 'json', // <- tell jQuery to expect json,
                      // and to build a js object from the answer
    success : function(obj){
       //obj is a regular js object, built from the received json
       obj[i].info.title; // <- accessing this piece of data
    }
});

If your data is sometimes json, sometimes something else :

success: function(data){
   var obj
   try {
       obj = JSON.parse(data);
       // if no exception is thrown, data was a valid json string,
       // and obj is a regular js object
       obj[i].info.title; // <- accessing this piece of data
   } catch (e) {
       // Maybe do something on error ?
   };
}

You can then build a html string like hsuk suggested :

var html = '';
for(i=0; i < obj.length; i++) {
    html += '<div class="item">';
    html += '<div class="title">' + obj[i].info.title + '</div>';
    html += '<div class="price">' + obj[i].info.price + '</div>';
    html += '</div>';       
}
alert.html(html).fadeIn();
Community
  • 1
  • 1
LeGEC
  • 46,477
  • 5
  • 57
  • 104
  • It will always be returned in JSON format, I was told that would be the best way to return the results so I can append the #resultsPanel when new results are found. I'll give that a whirl now and see how I get on. Thank you for your help. – MikeF Dec 10 '13 at 11:08
  • Following your advise I have finally succeeded in what I was out to achieve. Thank you. I have accepted your answer. – MikeF Dec 10 '13 at 11:25
0

Actually, the funny bit about JSON (JavaScript Object Notation) is that you can use it as is in Javascript.

Meaning, if your JSON string is {"foo": "bar"}, you can directly use it in Javascript like:

var myObject = {"foo": "bar"};

or

var myJSONString = '{"foo": "bar"}';
var myObject = eval(myJSONString);

But maybe you better go with JSON.Parse , as eval might be vulnerability if you are parsing User Data, that might not necessarily be in JSON format. (EG. Json data that is sent via HTTP, where the client could mess with ti.)

nl-x
  • 11,762
  • 7
  • 33
  • 61