fWd82
fWd82

Reputation: 850

Parse JSON data with jQuery

I have a web service which returns this JSON:

[{
    "user_id": "1",
    "user_name": "User1",
    "user_age": "20"
}, {
    "user_id": "2",
    "user_name": "User2",
    "user_age": "21"
}, {
    "user_id": "3",
    "user_name": "User3",
    "user_age": "24"
}, {
    "user_id": "4",
    "user_name": "User4",
    "user_age": "34"
}, {
    "user_id": "5",
    "user_name": "User5",
    "user_age": "27"
}]

What I want is I want to populate it to some list and also want to get index of list item clicked so that I can retrieve more information according to that index value (user_id).

What I did is:

function fetchFunction() {
    //fn.load('fetchPage.html');
    console.log("fetchFunction is invoked");

    var header = "<ons-list-header>My Inset ListTTT</ons-list-header>";

    $.ajax({
        type: 'POST',
        url: "fetchJSON.php",
        timeout: 5000,
        //dataType:'text',
        dataType:'json',
        success: function(data) {
             var data2 = JSON.stringify(data); //to string
             //var data2 = JSON.parse(data); //to string
             console.log("Index of list is: " + data2[0].user_id + " and username is: " + data2.user_name);         

             //alert("Index is: " + data[0]); 
             //$("#myListElement").html(header);
             //$("#myListElement").append(data);

             // Parse 'data' here
            console.log("SuccessED");
        },
        error: function(err) {
            ons.notification.alert("Error: " + err.status + ", " + err.statusText);
            console.log("Error: " + err);
            // console.log(err.status);
            // console.log(err.statusText);
            // $("#div1").text(err.responseText);
        }
    });
}

data2[0].user_id is doing nothing, just returning undefined.

I have a click function on that div called myListElement so I want to show the user_id on which the click function triggered.

if (event.target = "fetchPage2.html") {
        $("#myListElement").click(function(){
            alert("List Item Clicked!");
        });
    }

I will love if you give me some idea.

BTW I am using: Cordova + OnSenUI. :/

Thank You.

PS: I have this ons-list as a List. and want to populate it here.

<ons-list modifier="inset" id="myListElement">
    <ons-list-header >My Inset listdc</ons-list-header>
    <ons-list-item modifier="longdivider" tappable>Item A</ons-list-item>
    <ons-list-item modifier="longdivider" tappable>Item B</ons-list-item>
    <ons-list-item modifier="longdivider" tappable>Item C</ons-list-item>
</ons-list> 

Upvotes: 1

Views: 12470

Answers (5)

Patrick R
Patrick R

Reputation: 6857

You can parse json using $.parseJSON() function. Please check example given below:

$( document ).ready(function() {
        var data = '[{"user_id": "1","user_name": "User1","user_age": "20"}, {"user_id": "2","user_name": "User2","user_age": "21"}, {"user_id": "3","user_name": "User3","user_age": "24"}, {"user_id": "4","user_name": "User4","user_age": "34"}, {"user_id": "5","user_name": "User5","user_age": "27"}]';  
        var data2 = $.parseJSON(data);
                console.log("Print json data");
                  $.each(data2, function(i, item) {
                        console.log("Index of list is: " + item.user_id + " and username is: " + item.user_name + " and age is: " + item.user_age);      
                  });                        
                console.log("End print");
        });

Upvotes: 0

warl0ck
warl0ck

Reputation: 3464

After using the command JSON.stringify() function its no longer a array that you can access, If you are getting JSON object from the server you can directly access as objects like data[someindex].user_id.

If you are getting the data as string in that case you can use data = JSON.parse(data) Here is JSFIddle sample

To get the User details on clicking the user:

var data = [{
    "user_id": "1",
    "user_name": "User1",
    "user_age": "20"
}, {
    "user_id": "2",
    "user_name": "User2",
    "user_age": "21"
}, {
    "user_id": "3",
    "user_name": "User3",
    "user_age": "24"
}, {
    "user_id": "4",
    "user_name": "User4",
    "user_age": "34"
}, {
    "user_id": "5",
    "user_name": "User5",
    "user_age": "27"
}]
success(data);
function success(data) {
    console.log("Index of list is: " + data[0].user_id + " and username is: " + data[0].user_name);
    for(var i=0;i<data.length;i++) {
        $("#myListElement").append('<ons-list-item>' + data[i].user_name + '</ons-list-item>');

    }
}

$("#myListElement").on('click', 'ons-list-item', function() {
var index = $(this).index();
	console.log('selected user details: name:  ' + data[index].user_name + '  id: ' + data[index].user_id + '  age : ' + data[index].user_age);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<ons-list modifier="inset" id="myListElement">

</ons-list> 

Here is JSfiddle link as well.

Upvotes: 1

muratoner
muratoner

Reputation: 2682

If your service returned data with application/json then use direct data variable

console.log("Index of list is: " + data[0].user_id + " and username is: " + data[0].user_name);   

Test Code

var data = [{
    "user_id": "1",
    "user_name": "User1",
    "user_age": "20"
}, {
    "user_id": "2",
    "user_name": "User2",
    "user_age": "21"
}, {
    "user_id": "3",
    "user_name": "User3",
    "user_age": "24"
}, {
    "user_id": "4",
    "user_name": "User4",
    "user_age": "34"
}, {
    "user_id": "5",
    "user_name": "User5",
    "user_age": "27"
}]

console.log("Index of list is: " + data[0].user_id + " and username is: " + data[0].user_name);

If your service returned data with text then use convert data to Json with JSON.parse() function

var data2 = JSON.parse(data);
console.log("Index of list is: " + data2[0].user_id + " and username is: " + data2[0].user_name);  

Test Code

var data = '[{ "user_id": "1", "user_name": "User1", "user_age": "20" }, { "user_id": "2", "user_name": "User2", "user_age": "21" }, { "user_id": "3", "user_name": "User3", "user_age": "24" }, { "user_id": "4", "user_name": "User4", "user_age": "34" }, {"user_id": "5","user_name": "User5", "user_age": "27" }]'
var data2 = JSON.parse(data);
console.log("Index of list is: " + data2[0].user_id + " and username is: " + data2[0].user_name);

Upvotes: 2

Kinjal Akhani
Kinjal Akhani

Reputation: 168

<script
  src="https://code.jquery.com/jquery-3.2.1.min.js"></script>
<script>
    var myJSON = [{     "user_id": "1",     "user_name": "User1",     "user_age": "20" }, {     "user_id": "2",     "user_name": "User2",     "user_age": "21"              }, {     "user_id": "3",     "user_name": "User3",     "user_age": "24" }, {     "user_id": "4",     "user_name": "User4",     "user_age":              "34" }, {     "user_id": "5",     "user_name": "User5",     "user_age": "27" }];
    function fetchFunction(){
        $('#myListElement tbody').empty();
        $.each(myJSON,function(ind,obj){
            var htmlTemplate = "<tr userID=" + obj.user_id + " onClick='displayUserData(this)'><td></td><td>" + obj.user_id + "</td><td>"+ obj.user_name +"</td><td>"+ obj.user_age +"</td></tr>"
            $('#myListElement').append(htmlTemplate);
        });
    }
    function displayUserData(ref){
        myTr = ref;
        alert("User ID :: "+ $(ref).attr('userID') +" Row is Click");
    }
</script>
<input type="button" onClick="fetchFunction()" value="Fetch Data">
<table id="myListElement" border="1" cellspacing="0" cellpadding="10">
    <thead>
        <th>My Inset listdc</th>
        <th>Item A</th>
        <th>Item B</th>
        <th>Item C</th>
    </thead>
    <tbody>

    </tbody>
</table>

Upvotes: 1

Theodore K.
Theodore K.

Reputation: 5176

With this small change your code works:

var data2 = JSON.stringify(data);
data2 = $.parseJSON(data2);
console.log("Index of list is: " + data2[0].user_id + " and username is: " + data2[0].user_name);      

Output: Index of list is: 1 and username is: User1

Demo: http://codepen.io/8odoros/pen/GWLmwB

Upvotes: 1

Related Questions