Stacy J
Stacy J

Reputation: 2781

Accessing a JSON element inside JSON

I am getting data stored in MySQL database from a PHP script using jQuery ajax. I am parsing the data returned in JSON format and displaying it in a table.

The problem is one of the element is stored in json format so MySQL returns the entire data and it is displayed in the same manner.

$.each(data, function (key, element) {
    $('table').append('<tr><td>' + element.aid + '</td><td>' + element.userid + '</td><td>' + element.atitle + '</td><td>' + element.atype +  '</td><td>' + element.adata + '</td></tr>');  
});

element.adata is being displayed in the following manner :

{
    "click_title":"GO",
    "links": {
        "commonlink":"http:\/\/bookings.com",
        "alllinks": [
            [{
            "link1":"http:\/\/xyz1.com\/get\/a",
            "link2":"http:\/\/www.anotherwebsite1.com\/c\/t",
            "link3":"http:\/\/www.newsite1.com\/v\/h"
            },{
            "link1":"http:\/\/xyz2.com\/get\/a",
            "link2":"http:\/\/www.anotherwebsite2.com\/c\/t",
            "link3":"http:\/\/www.newsite2.com\/v\/h"
         }],[{
            "link1":"http:\/\/xyz3.com\/get\/a",
            "link2":"http:\/\/www.anotherwebsite3.com\/c\/t",
            "link3":"http:\/\/www.newsite3.com\/v\/h"
         }]
        ]
    }
}

How do I access the links so that I can display them in a better way?

Upvotes: 0

Views: 69

Answers (1)

Darin Dimitrov
Darin Dimitrov

Reputation: 1038840

You could parse the JSON string to a javascript object using the $.parseJSON() function:

var data = $.parseJSON(element.adata);

and then access individual elements. For example:

data.links[0][0].link1

or if you don't know the number of elements in advance you could also loop through them using $.each.

Upvotes: 1

Related Questions