user3312993
user3312993

Reputation: 1

Javascript how to parse JSON with json array

I want to parse this using jQuery or javascript My JSON generated from the PHP code is as follows:

JSON

{
         "user": {
             "name": "John Carter",
             "position": 0,
             "tickets": {
                 "months": [
                     "October",
                     "November"
                 ],
                 "start_Time": "2014-10-02",
                 "end_Time": "2014-11-21",
                 "Open": [
                     "1",
                     "3"
                 ]
             }
         }
}

My Javascript

$.ajax({
                url: 'ajax.report.php',
                type: 'POST',
                data: 'start='+startDate+'&&end='+endDate,
                success: function(response){
                    var json_obj = $.parseJSON(response);
                    for(var i =0; i < json_obj.user.length; i++){
                        //What is the next?
                    }
                }
            });

Kindly help. Thank you !

Upvotes: 0

Views: 77

Answers (3)

AmuletxHeart
AmuletxHeart

Reputation: 406

The json returned by jQuery is already a JavaScript object, not a string. You do not have to parse it any further to use it. I'm on a mobile device right now so I can't confirm, but I'm pretty sure you can just do this:

success: function(response){
    //try
    var name = response.user.name
    //try this as well
    var name = response.name
}

You should be able to print out the name string using console.log() after this.

Upvotes: 1

Niels
Niels

Reputation: 101

I suggest that you look over the jquery docs for more info, the best thing you can use is jquery.ajax Make sure that in your php script you encode the text as JSON, otherwise jquery will interpret it as plain/text.

Little snippet, which you can also find on the jquery docs..

$.ajax( "example.php" )
.done(function(data) {
    console.log(data);
});

Upvotes: 0

Arvoreniad
Arvoreniad

Reputation: 510

I'm assuming that you're trying to convert some JSON in string form to an object usable by JS. You can parse a valid JSON string into a JS object by using JSON.parse(jsonString). (Where jsonString is a variable containing the string of JSON)

Upvotes: 0

Related Questions