Click here to Skip to main content
15,886,012 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
"items":[  
      {  
         "id":"1",
		 "obj":{
         "json":"1.json",
         "js":"1.js",
         "css":"1.css",
         "text":"1.txt",
        
		 }
      },
      { 
       "id":"2",
		 "obj":{
         "json":"2.json",
         "js":"2.js",
         "css":"2.css",
         "text":"2.txt",
		 }
      }
   ]

if i passs id=1 then it should display 
"json":"1.json",
         "js":"1.js",
         "css":"1.css",
         "text":"1.txt", this
Posted

1 solution

To parse a JSON value, use JSON.parse. Then loop over all items to find the data you need:
JavaScript
var items = JSON.parse(yourJsonString).items;
var idToSearch = "1";
for (var i = 0; i < items.length; i++) {
    if (items[i].id == idToSearch) {
        var foundData = items[i].obj;
        // now display foundData where you want to display it
    }
}

Also, your JSON string is invalid. There is a comma without data after it, and the outer object should be wrapped within {} braces. So, this data is valid:
C#
{
    "items": [
        {
            "id": "1",
            "obj": {
                "json": "1.json",
                "js": "1.js",
                "css": "1.css",
                "text": "1.txt"
            }
        },
        {
            "id": "2",
            "obj": {
                "json": "2.json",
                "js": "2.js",
                "css": "2.css",
                "text": "2.txt"
            }
        }
    ]
}
 
Share this answer
 
v2
Comments
kiran gowda8 25-May-15 6:35am    
var jsontxt = '{"items":[{"id": "1","obj": {"json": "1.json","js": "1.js","css": "1.css","text": "1.txt"}},{"id": "2","obj":{"json": "2.json", "js": "2.js","css": "2.css","text": "2.txt"}}]}';

function getvalue(id) {
var items = JSON.parse(jsontxt).items;
for (var i = 0; i < items.length; i++) {
if (items[i].id == id) {
var data = items[i].obj;

alert(data);
}
}

}

this is what i tried but its not displaying the output. its showing only [object, object]
Thomas Daniels 25-May-15 6:36am    
That's because you are trying to display the object directly. foundData is an object, that contains the data you're looking for.
kiran gowda8 25-May-15 6:46am    
yup.. solved.. thank you soo much programFOX
Maciej Los 25-May-15 17:55pm    
5ed!

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900