Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get JSON object by attribute

Say I have this JSON object:

var images = {"success":"true", "images":[
     {"id":"1234","url":"asdf","tags":["cookie","chocolate"]},
     {"id":"5678","url":"qwer","tags":["pie","pumpkin"]}
]};

What would be the most efficient way to get the url of the image with an id of 5678? Can use jQuery.

like image 490
penguinrob Avatar asked Sep 17 '11 03:09

penguinrob


People also ask

How do you access the attribute of a JSON object?

To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.

How do you access a JSON object in Python?

Reading From JSON It's pretty easy to load a JSON object in Python. Python has a built-in package called json, which can be used to work with JSON data. It's done by using the JSON module, which provides us with a lot of methods which among loads() and load() methods are gonna help us to read the JSON file.

What is an attribute in JSON?

JSON-related attributes specify the use of variable attributes in JSON functions and control output that is generated by JSON functions. JSONNAME attribute. The JSONNAME attribute specifies the name that is used or expected for a variable in jsonPut or jsonGet functions.


2 Answers

Because it's an array and you're looking for an embedded property, not just a simple array value, there isn't really a super-efficient way to find it. There's the brute force mechanism of just walking through the array and compare each id to what you're looking for.

If you're going to be looking up these kinds of things in this same data structure multiple times and you want to speed it up, then you can convert the existing data structure into a different data structure that's more efficient for accessing by ID like this:

var imagesById = {
    "1234": {"url":"asdf","tags":["cookie","chocolate"]},
    "5678": {"url":"qwer","tags":["pie","pumpkin"]}
}

Then, finding an object by id is as simple as this:

imagesById["1234"]
like image 145
jfriend00 Avatar answered Oct 10 '22 05:10

jfriend00


url = $.grep(images.images, function(item) { return item.id === '5678' })[0].url;
like image 23
user123444555621 Avatar answered Oct 10 '22 04:10

user123444555621