I am trying loop through the following JSON file below:
{
"statements": [{
"subject": "A"
}, {
"predicate": "B"
}, {
"object": "C"
}, {
"subject": "D"
}, {
"predicate": "E"
}, {
"object": "F"
}]
}
As you can see, there are two subjects, two predicates and two objects. I would like to get, for instance, the value "predicate":"E". How can I do this using jQuery or D3 Javascript library. My code below retrieves the first subject "subject":"A".
$.each(data.statements[0], function(i, v){
console.log(v.uriString);
});
or in D3 (I do not know how to do this in D3):
d3.json("folder/sample.json", function(error, graph)
{ // Code is here for getting data from JSON file }
Could anyone please help me loop through the JSON file above and retrieve some particular data either with jQuery or D3 Javascript. Thank you for your help in advance.
Try this:
$(data.statements).each(function (i) {
var d = data.statements[i];
$.each(d, function (k, v) { //get key and value of object
$("body").append("<p>"+k + ":" + v+"</p>");
});
})
Fiddle here.
The reason why your code returns the first item is beacuse you selected it with data.statments[0] and afterwards loop over that one item.
With jQuery you can use the grep-method like this:
var arrayWithItem = jQuery.grep(data.statements, function( obj ) {
return obj.predicate == "E";
});
You can read more about the grep-method here
With D3js I'm not sure, I guess you have to loop through it with an if-statement.
Related
SITUATION:
I have dynamic json object data and need to use it to find element.
Example:
[
{ "tag": "article",
"id": "post-316",
"order": "0" },
{ "tag": "div",
"class": "entry-content",
"order": "0" }
]
Its length, keys and values can change anytime based on user request.
I need to use that data to dynamically find the specified element in a web page. The first set of strings will be the data for parent element, which will be used to initialize the search, and the last one will be the target children.
PURPOSE:
So, from json example above, I want to find an element with:
class name entry-content, tag name div, index 0 inside of parent with id post-316
by converting that json data in such kind of format or may be simpler and or better:
// because the parent already have attribute id, so no need to check other info of this element
var elem = $("#post-316").find(".entry-content");
if(elem.prop("tagName") == "div" ) {
elem.css("background", "#990000");
}
PROGRESS:
I tried using jquery $.each() method but can't discover myself the way to achieve that purpose.
Here is the code where I currently stuck on:
var json = $.parseJSON(theJSONData);
$.each(json, function(i, e){
$.each(e, function(key, data){
alert(i + " " + key + " " + data);
if(json.length - i == 1) {
alert("target " + data);
}
if(json.length - i == json.length) {
alert("parent " + data);
}
}
);
});
QUESTIONS:
Is it possible to achieve the PURPOSE from that kind of JSON data using iteration?
If it is possible, how to do it?
If not, what the way I can use?
You can use a format so the script knows what to get:
var data = {
'id': '#',
'class': '.'
};
var json = JSON.parse(theJSONData);
$.each(json, function (a) {
$.each(data, function (b) {
if (a[b]) {
$(data[b] + a[b])[+a['order']]; // Element
}
});
});
If you are sure about the data you are getting (As in it is class, or data, and it will have a tag name):
var json = JSON.parse(theJSONData),
last = document;
$.each(json, function (a) {
var selector = (a['id']) ? '#'+a['id'] : '.'+a['class'];
last = $(last).find(a['tag']+selector)[+a['order']]; // Element
});
I created product database with JSON:
{
"1": {"group":"1", "name":"bmw" },
"2": {"group":"1", "name":"audi"},
"3": {"group":"2", "name":"volvo"}
}
But now I need to create an HTML drop down with all elements by group id.
I tried using Javascript .grep() but I don't have enough experience how to do that. Any help?
var all;
$.getJSON("data.json", function( data ) {
all = data;
});
var group1 = $.grep(all, function(el, i) {
return el.group. === 2
});
console.log(JSON.stringify(group1));
According to the documentation $.grep is for use with arrays, coincidentally it also has several clear examples... your JSON object is not an array but an object literal. Ideally instead of this:
{
"1": {"group":"1", "name":"bmw" },
"2": {"group":"1", "name":"audi" },
"3": {"group":"2", "name":"volvo"}
}
Your response should be coming back similar to this:
{
products: [
{"group":"1", "name":"bmw" },
{"group":"1", "name":"audi" },
{"group":"2", "name":"volvo"}
]
}
Then with a little tweaking your example will return the object's you desire in another array - take note of the difference between the === and the == operators as in your JSON example the group is returned as a string as opposed to a number.
var group1 = $.grep(all.products, function(el, i){
return el.group == 2;
});
If you still wish to work with your original JSON object (which you shouldn't as it's keys seem redundant and somewhat inefficient), then you will have to devise your own method of filtering. For example:
var group1 = {};
$.each(all, function(i, el){
if(el.group == 2) group1[i] = el;
});
So I've got a JSON file that gets parsed into an object in Javascript. I know what you're thinking: lucky guy. The JSON is essentially a flow diagram in a big tree form. Here's tiny a sample of what I'm trying to achieve:
tree = {
"options": [
{
"options": [
{
"name": "target",
},
],
},
{
"options": [
{
"link": "...?",
},
],
},
]
}
So in this example, I'll be deep in the second branch (where it says "link") and I'll want to be able to jump to the branch that contains "name": "target". This is JSON remember so it'll need to be a string (unless there's a native for linking?! is there?) but I don't know how best to format that.
As I see it, I've got at least a couple of options.
I could search. If name was unique, I could scale the tree looking for elements until I found it. I've never done with with Javascript before but I expect it to be slow.
I could use a navigation path like options:1:options:1 that describes each key for the path. Again, I've never done this but, assuming there are no errors, it would be a lot faster. How would you implement it?
Are there any other options available to me? What seems best? Is there a way to unpack this when JSON decoding, or is that a recipe for an infinite loop?
What about link: 'tree.options[0].options[0]' then eval(path.to.link)?
Following samples were tested with Chrome only. Same tree for all :
var tree = { level1: [{ key: 'value' }] };
No eval
function resolve(root, link) {
return (new Function('root', 'return root.' + link + ';'))(root);
}
var value = resolve(tree, path.to.link);
Fallback to window
function resolve(root, link) {
return (new Function(
'root', 'return root.' + (link || root) + ';'
))(link ? root : window);
}
resolve(tree, 'level1[0].key'); // "value"
resolve('tree.level1[0].key'); // "value"
Catching errors
The try/catch block prevents broken links from throwing errors.
function resolve(root, path) {
try {
return (new Function('root', 'return root.' + path + ';'))(root);
} catch (e) {}
}
resolve(tree, 'level1[0].key'); // "value"
resolve(tree, 'level1[1].key'); // undefined
Using custom path format
The good part here is that we can pass either an object or an array as root. Also note that we can replace the slash in path.split('/') with any char of our choice.
function resolve(root, path) {
path = '["' + path.split('/').join('"]["') + '"]';
return (new Function('root', 'return root' + path + ';'))(root);
}
resolve(tree.level1, '0/key'); // "value"
resolve(tree, 'level1/0/key'); // "value"
resolve(tree, 'level1/0'); // Object {key: "value"}
Given a JSON string as this:
{
"__ENTITIES": [
{
"__KEY": "196",
"__STAMP": 1,
"ID": 196,
"firstName": "a",
"middleName": "b",
"lastName": "c",
"ContactType": {},
"addressCollection": {
"__deferred": {
"uri": "/rest/Contact(196)/addressCollection?$expand=addressCollection"
}
},
"__ERROR": [
{
"message": "Cannot save related entity of attribute \"ContactType\" for the entity of datastore class \"Contact\"",
"componentSignature": "dbmg",
"errCode": 1537
}
]
}
]
}
Is there a method to get just the __ERROR record, I know I can use
var mydata = json.parse(mydata) and then find it from the mydata object. But I was hoping there was a method to only return the ERROR field something like
json.parse(mydata, "__ERROR") and that gets only the information in the __ERROR field without turning the whole JSON string into an object
"Is there a method to get just the __ERROR record, I know I can use var mydata = json.parse(mydata) ... But I was hoping there was ... something like json.parse(mydata, "__ERROR")"
There may be libraries that do this, but nothing built in. You need to write code that targets the data you want.
The closest you'll get will be to pass a reviver function to JSON.parse.
var errors = [];
var mydata = JSON.parse(mydata, function(key, val) {
if (key === "__ERROR")
errors.push(val);
return val
});
without turning the whole json string into an object
That's hardly possible, you would need some kind of lazy evaluation for that which is not suitable with JS. Also, you would need to write your own parser for that which would be reasonable slower than native JSON.parse.
Is there a method to get just the __ERROR record
Not that I know. Also, this is an unusual task to walk the whole object tree looking for the first property with that name. Better access __ENTITIES[0].__ERROR[0] explicitly.
If such a function existed, it would have to parse the whole thing anyway, to find the key you're looking for.
Just parse it first, then get the key you want:
var mydata = JSON.parse(mydata);
var errorObj = mydata.__ENTITIES[0].__ERROR[0];
If you want, you may create your own function:
function parseAndExtract(json, key) {
var parsed = JSON.parse(json);
return parsed[key];
}
All,
I've got a function that basically gets triggered when an Upload finishes. I have the following code in that function:
onFinish: function (e, data) {
console.log(data.result);
},
When I do this I get the following response in my console:
[{
"name": "1_3266_671641333369_14800358_42187036_5237378_n.jpg",
"size": 35535,
"type": "image\/jpeg",
"url": "\/web\/upload\/1_3266_671641333369_14800358_42187036_5237378_n.jpg",
"thumbnail_url": "\/web\/upload\/thumbnails\/1_3266_671641333369_14800358_42187036_5237378_n.jpg",
"delete_url": "\/web\/upload.php?file=1_3266_671641333369_14800358_42187036_5237378_n.jpg",
"delete_type": "DELETE",
"upload_type": "video_montage"
}]
I'd like to get the value that is in the upload_type and do some actions based on that but I'm not sure how to get this from my function. Any help would be appreciated to get this information.
Thanks!
data.result is an array, you need to access the first element and then access upload_type.
Try console.log(data.result[0].upload_type);
Update:
If data.result is a string, you need to parse it first.Try
var result = JSON.parse(data.result);
console.log(result[0].upload_type);
You would access the upload_type property by the following:
onFinish: function (e, data) {
var uploadType = data.result[0].upload_type;
},
data.result[x] specifies to grab the object within the x key of your array. If you had multiple objects within your array then you would utilize a for loop to iterate each key.
To access the other properties you would follow the same principle. Based off of the desired action, you will handle the data appropriately.
Edit: What does the following return?
var obj = data.result[0];
for(var item in obj){
console.log(item + ': ' + obj[item]);
}
Demo: http://jsfiddle.net/yYHmQ/