Working With JSON in JavaScript
We'll use older, more familiar, JS notation
Remember: JavaScript JSON objects are not strings
var json = {
'meta': {'id': 'yo', 'stuff': 'njunk', 'user': '2929234823892389'},
'entities': [{
'id': '1',
'url': 'www.facebook.com',
'exampleArray': {
'a': 'aa'
}
}, {
'id': '2',
'url': 'www.google.com',
'exampleArray': {
'b': 'bb'
}
}]
};
Give it a Name
The example above displays meta information
Also a list of (sub) JSON entities that we're going to put into some logic
We'll refer to them by this variable name:
var entities = json.entities;
Make a Helper
We now create a helper function to show a popup
('stringify' converts JSON objects to strings)
var alertJSON = function(json) {
return alert(JSON.stringify(json));
};
Build the Logic
Our main logic iterates through the array searching for the id passed in as parameter b
We also want to make sure that the 'array' data field exists on the selected entity
The JSON array is non-null
(add a null-check if the situation were otherwise)
var fetchFromArrayById = function(a, b) {
var entity;
for (var key in a) {
//Find the desired JSON object in the array
if (a[key].id == b) {
entity = a[key];
}
}
//Check the JSON object for a field
if ('exampleArray' in entity) {
alertJSON(entity);
}
};
Make the Call
Here we make our call to display the first object in the array:
fetchFromArrayById(entities, 1);