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.
To access the JSON object in JavaScript, parse it with JSON. parse() , and access it via “.” or “[]”.
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.
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.
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"]
url = $.grep(images.images, function(item) { return item.id === '5678' })[0].url;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With