简体   繁体   中英

how to parse following JSON data using Jquery

I am new on JQuery. I have this JSON response from the server how could I parse it?

[
    {
        "note": {
            "created_at": "2012-04-28T09:41:37Z",
            "updated_at": "2012-04-28T09:41:37Z",
            "text": "aaaaaaaaaaafdafasd fasfasd dfa sdfasf asdfa fasdfda",
            "lng": 44.5159794497071,
            "id": 7,
            "deleted": false,
            "user_id": 1,
            "note_type": "text",
            "lat": 40.1884140543842
        }
    },
    [ ... more JSON ...]
]

How could I parse this?

You have to set the data type of the request to "json", and the data will be already parsed in your success callback.

Everything you need to know at the moment is on http://api.jquery.com/jQuery.ajax/

Here is a very simple example of what you can do:

$.ajax({
    url: url, // the service URL. Must answer proper JSON
    data: {  // the parameters of the request. This should be adapted to your case
        param1: value1,
        param2: value2
    },
    dataType: "json",
    type: "POST",
    success: function(resultData) {
        // here, resultData is your parsed json
    },
    error: function() {
        // handle error here
    }
});

jQuery.parseJSON

Use this jQuery method to parse JSON objects.

If the server outputs actual JSON (the example in the question has errors) and it has the correct content type ( application/json rather then the text/html that PHP defaults to) then you don't need to do anything.

jQuery will parse it for you (and present you with a JavaScript object in the success handler).

That's not JSON. What you have posted looks like a PHP array that had brackets wrapped around it to try to make it into JSON.

Use this site to validate your JSON in the future.

Now, to get your PHP array into JSON, use json_encode() and dispatch it to the browser with a specific header.

$array = array( 'test' => 'sure' );
header('Content-type: application/json');
print json_encode($array);
exit;

Now, you'll have actual JSON with which you can use in JavaScript.

$.get(  'yourFile.php',
        function(data){
            console.log(data);
        }
);

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