Saturday 30 April 2016

How To Read Json File Into Javascript Arrray



Contacts.json File 


{
    "ppl1":{
        "Name":"Jhon",
        "Surname":"Kenneth",
        "mobile":329129293,
        "email":"jhon@gmail.com"
    },
    "ppl2":{
        "Name":"Thor",
        "Surname":"zvalk",
        "mobile":349229293,
        "email":"thor@gmail.com"
    },
    "ppl3":{
        "Name":"Mila",
        "Surname":"Kvuls",
        "mobile":329121293,
        "email":"mila@gmail.com"
    }
}

Read / Parse Json File into Javascript Array


Use The Code Below To Read Json File ( Contacts.json  ) . File Data Shown Above into Javascript Array

$.getJSON('contacts.json', function (json) {
var array = [];
for (var key in json) {
    if (json.hasOwnProperty(key)) {
        var item = json[key];
        array.push({
            name: item.Name,
            surname: item.Surname,
            mobile: item.mobile,
            email: item.email
        });            
    }
}
});
Here getJSON will make a ajax request to contacts.json file and file contents is shown above in the post . Ajax request will get json data from the file and output that data to 'json' object . In code i am making an empty array then opening a for loop through the json object that contains data that ajax request has read from contacts.json file then we are pushing data from json object to newly created array
 That way we will be having data in new created Javascript array from json file

Share this

0 Comment to "How To Read Json File Into Javascript Arrray"

Post a Comment