简体   繁体   中英

Parse External JSON File with jQuery

I have a 2 MB JSON object that I'm hoping to parse with jQuery. I dumped the whole object into a file named "timeline.js" and I'm hoping to parse through it as a dataset to grab records as needed.

My dataset started as an XML file, but I read that JSON would be more efficient as I'm using jQuery to pull the data and place it in the DOM.

Below is the first record of my object. How would I parse this object to grab the record with a 'profileid' of 1016?

{
timeline:{
    record:[
        {
            profileid:1016,
            title:'Adam',
            parentprofileid:0,
            type:'Person',
            minzoomlevel:29,
            maxzoomlevel:66,
            isapproxstart:1,
            isapproxend:1,
            startdate:-4181,
            enddate:-3251,
            shortdescription:'Name means "red" or "man" he is...',
            article:'<div><span>The first member of...',
            status:22,
            scriptures:{
                scripture:[
                    {
                        profileid:1016,
                        scripturetext:'Genesis 2:7',
                        referencetext:'Birth'
                    },
                    {
                        profileid:1016,
                        scripturetext:'Genesis 5:4',
                        referencetext:'Death'
                    }
                ]
            }
        },

jQuery parseJSON works fine, however is unnecessary when using jQuery AJAX and set the dataType to JSON (it is already parsed by jQuery after receiving the data).

However, I guess your actual question is how to find the record with the profileid of eg 1016. Since all items are in an array, the only way to find it, is to loop the array and check what profileId is set for the current item. For example:

for(var i in items){
    if(items[i].profileid == 1016){
       //execute whatever you want to do.
    }
}

Make use of : jQuery.parseJSON( json ) - Takes a well-formed JSON string and returns the resulting JavaScript object. Example

var obj = jQuery.parseJSON('{"name":"John"}');
 alert( obj.name === "John" );

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