-2

I have JSON data in a local file, and I have success to load using jQuery. Now I need to search pId = "foo1" only.

JSON

{
 "1":{
      "id": "one",
      "pId": "foo1",
      "cId": "bar1"
     },
 "2":{
      "id": "two",
      "pId": "foo2",
      "cId": "bar2"
     },
 "3":{
      "id": "three",
      "pId": "foo3",
      "cId": "bar3"
     }
}

jQuery

id = "1"; // Or whatever
var entry = objJsonResp[id];

console.log(entry);


But it shows id, pId and cId values and I only need the pId value, not other.
So what is the best way to get the value of pId

Hunter Turner
  • 6,804
  • 11
  • 41
  • 56
webdevanuj
  • 675
  • 12
  • 22

4 Answers4

1

Calling objJsonResp[id] returns the whole first object.

Try using:

console.log(entry.pId);
spencer.sm
  • 19,173
  • 10
  • 77
  • 88
0
obj = JSON.parse("{\"1\":{\"id\": \"one\",\"pId\": \"foo1\",\"cId\": "bar1"},"2":{"id": "two","pId": "foo2","cId": "bar2"},"3":{"id": "three","pId": "foo3","cId": "bar3"}}");
// These \ are called escape chars, they say javascript that " is part of string.

After this you've got object of your JSON, so you have one parent object [obj] and 3 children objects ["1","2","3"] with properties of id,pId,cId. To get property of child you want to do it like parent[child_name][property_name] like this:

pid1 = obj["1"]["pId"];  // returns foo1
pid2 = obj["2]["pId"]; //return foo2

But what you asked for is JSON.parse() function, which gives you object representing your JSON

Marko Mackic
  • 2,293
  • 1
  • 10
  • 19
0

So i have solved by help @Hackerman and @prashkr
Both comments are right.
So final solution to get only value of pId as asked by me is to target it like this that are provide in comments above.

console.log(entry.pId);
console.log(entry['pId']);
webdevanuj
  • 675
  • 12
  • 22
-3

Obviously, the server, with whom you are communicating, is the (only) one who can return the appropriate set of results to you.   Therefore, your communication with the server must (somehow) include that search criteria, so that the server’s reply will only include the records of interest.   This will require additional programming on your part, on both the client and the server sides . . .

Mike Robinson
  • 8,490
  • 5
  • 28
  • 41