From the example JSON below, I would like to return the target.id value of an object where the source.id == 'x'.
So where source.id == 'startId' return target.id == '3eecd840-e6a8-423c-a892-7df9646fde5d'.
{
"line":[
{
"type":"link",
"source":{
"id":"startId",
"port":"out"
},
"target":{
"id":"3eecd840-e6a8-423c-a892-7df9646fde5d",
"port":"in"
},
"id":"87d88a26-3a28-4db0-8016-71c1c4665f14"
},
{
"type":"link",
"source":{
"id":"3eecd840-e6a8-423c-a892-7df9646fde5d",
"port":"outYes"
},
"target":{
"id":"49940c02-70f2-4c53-ab50-9cbf96903600",
"port":"in"
},
"id":"9f8c365e-9ca7-440f-a722-c4f340782c0c"
}
]
}
I've tried JSONPath, but I cannot work out the expression to use. $.line[*].source.id gives me a list of source id's and $.line[?(#.source.id=='startId')] returns an error.
I also understand that I could iterate through each object in code, but It wouldn't be very efficient if I have tens or hundreds of 'lines' to work through. If possible I would like a more 'direct' path to the object.
I'm using javascript to code the rest of the app, so javascript examples would be helpful (with or without JSONPath).
If you're getting json as string, then use var json = JSON.parse(jsonStr). Then you can do it with Array.filter
var result = json.line.filter(function(obj){
return obj.source.id == "startId"
});
Then you could get the values like this
var ids = result.map(function(o){ return o.target.id });
Related
I have a JSON data set as follows:
{
"content":[],
"layout":[],
"trail":[
{
"content":[
{
"type":"image",
"media":[
{
"type":"image/jpg",
"width":593,
"height":900,
"url":"https://live.staticflickr.com/65535/48208920877_e6b234d3ea_c_d.jpg",
"flickr":{
"flickr-post":"https://www.flickr.com/photos/riketrs/48208920877",
"flickr-album":"https://www.flickr.com/photos/riketrs/albums/72157709130951466"
}
}
]
},
{
"type":"image",
"media":[
{
"type":"image/jpg",
"width":1600,
"height":900,
"url":"https://live.staticflickr.com/2817/33807326532_91013ef6b1_h_d.jpg",
"flickr":{
"flickr-post":"https://www.flickr.com/photos/146758538#N03/33807326532",
"flickr-album":"https://www.flickr.com/photos/146758538#N03/albums/72157681438471236"
}
}
]
}
],
"colors":{
"c0":"#1e1e1d",
"c1":"#78736f",
"c2":"#b2a89f"
}
}
]
}
I would like to console.log the "url" key for each of the images shown here.
(https://live.staticflickr.com/65535/48208920877_e6b234d3ea_c_d.jpg and https://live.staticflickr.com/2817/33807326532_91013ef6b1_h_d.jpg)
I tried some code but I'm very new to JSON in general, I've looked at some other answers to do with JSON but I'm not quite sure how to achieve what I want.
JSFiddle: https://jsfiddle.net/fj6qveh1/1/
I appreciate all advice, including links to other answers that I potentially missed.
Thank you!
url is a property of an object. There can be many of these in a media array. (This data only shows one object per array.) media itself is an property of objects inside the content array.
Use map, and flatMap.
map to return the URL values from the objects in media, and flatMap to return a flat array of the nested arrays returned by map.
const data={content:[],layout:[],trail:[{content:[{type:"image",media:[{type:"image/jpg",width:593,height:900,url:"https://live.staticflickr.com/65535/48208920877_e6b234d3ea_c_d.jpg",flickr:{"flickr-post":"https://www.flickr.com/photos/riketrs/48208920877","flickr-album":"https://www.flickr.com/photos/riketrs/albums/72157709130951466"}}]},{type:"image",media:[{type:"image/jpg",width:1600,height:900,url:"https://live.staticflickr.com/2817/33807326532_91013ef6b1_h_d.jpg",flickr:{"flickr-post":"https://www.flickr.com/photos/146758538#N03/33807326532","flickr-album":"https://www.flickr.com/photos/146758538#N03/albums/72157681438471236"}},{type:"image/jpg",width:1600,height:900,url:"https://live.dummyimage.com/2817/dummy.jpg",flickr:{"flickr-post":"https://www.flickr.com/photos/146758538#N03/33807326532","flickr-album":"https://www.flickr.com/photos/146758538#N03/albums/72157681438471236"}}]}],colors:{c0:"#1e1e1d",c1:"#78736f",c2:"#b2a89f"}}]};
const content = data.trail[0].content;
const urls = content.flatMap(obj => {
return obj.media.map(inner => inner.url);
});
console.log(urls)
The easiest way is to use map function. Given that you are very new to programming (the solution has little to do with JSON itself, since the first step is to parse JSON string to a JavaScript object), it would be better if you try yourself. But you start with
let urls = trail["content"].map(x => x["media"][0]["url"])
for more about map function look here
There is a table in the table so for each table:
for(let i in trail){
var content = trail[i]["content"];
content.forEach(content => content.media.forEach(media => console.log(media.url)))
}
To access object properties, you can use a dot (.), and to access an array element, you use its index in square brackets ([]). So you just keep repeating these steps as necessary until you get to the content you're looking for.
Here's how that looks on a simplified version of your object, using the forEach method of arrays to apply a custom function to each item in the content array:
const json = getJson();
json.trail[0].content.forEach(item=>console.log(item.media[0].url));
function getJson(){
let obj = {
"trail": [{
"content": [
{ "media": [{ "url":"image #65535/48208920877_e6b234d3ea_c_d.jpg" }]},
{ "media": [{"url":"image #2817/33807326532_91013ef6b1_h_d.jpg"}]}
]
}]
};
return obj;
}
[
{ comicid: "5f55e91271b808206c132d7c", purchasetype: "pb_single" }
]
Above is my JSON Array that is stringified,I tried to JSON.parse and other functions like iterating it in a for loop but the key values also got scrambled.
Is there any way or an npm method that could instantly output the retrieved variable?
var cartItemFromLocalStorage = JSON.parse(localStorage.getItem("cartitem"));
if (cartItemFromLocalStorage != null) {
console.log("It came defined");
console.log("This is OG Array: " + cartItemFromLocalStorage);
let cartItemObject = {
//set object data
comicid: this.state.comicId,
purchasetype: this.state.purchaseType,
};
console.log(cartItemObject);
cartItemFromLocalStorage.push(cartItemObject);
localStorage.setItem("cartitem", result); //localstorage only supports strings
toast.success("Item Added to cart");
}
I checked the consoles and the states are putting up the data correctly.
I'm an extreme beginner in react js, help is much appreciated
The "JSON" you have written is actually JavaScript, not JSON. To convert it JSON use the JSON.stringify function, like so
> JSON.stringify([
{ comicid: "5f55e91271b808206c132d7c", purchasetype: "pb_single" }
]);
'[{"comicid":"5f55e91271b808206c132d7c","purchasetype":"pb_single"}]'
and then replace the value in localStorage with it.
Even easier would be to type into the developer console
localStorage.setItem("cartitem", JSON.stringify([
{ comicid: "5f55e91271b808206c132d7c", purchasetype: "pb_single" }
]));
I am trying to find a match inside this JSON array but I find it a bit complicated since it's a nested array of objects.
I'm not sure what I am doing entire wrong here:
The idea is that I have an array with a set of permissions and I want to return only the set of permissions that match the role:
var data = [{
"visitor": {
"static": ["page-one:visit", "home-page:visit", "login"]
}
}, {
"users": {
"static": ["posts:list", "posts:create", "users:getSelf", "home-page:visit", "dashboard-page:visit"]
}
}, {
"admin": {
"static": ["posts:list", "posts:create", "posts:edit", "posts:delete", "users:get", "users:getSelf", "home-page:visit", "dashboard-page:visit"]
}
}]
var role = "admin"
for(var x=0;x <data.length;x++){
if(role === data[x]){
console.log("OLE, we got a match!" + data[x])
}
}
For some reason I just can't find a match. I just wanna return the full object like:
"admin":{
"static": ["posts:list", "posts:create", "posts:edit", "posts:delete", "users:get", "users:getSelf", "home-page:visit", "dashboard-page:visit"]
}
Here is a JS Bin Link.
You could use the .find function like below:
data.find(function(x){ return Object.keys(x).indexOf(role) > -1; });
Given your role is the key of the object, you need to check if the object itself contains the role as a key, for this you'd use Object.keys(<object>).indexOf(role) where indexOf will return the value of -1 if it's not found and 0+ if found.
var data = [{"visitor":{"static":["page-one:visit","home-page:visit","login"]}},{"users":{"static":["posts:list","posts:create","users:getSelf","home-page:visit","dashboard-page:visit"]}},{"admin":{"static":["posts:list","posts:create","posts:edit","posts:delete","users:get","users:getSelf","home-page:visit","dashboard-page:visit"]}}]
var role = "admin"
var admins = data.find(function(x){ return Object.keys(x).indexOf(role) > -1; });
console.log(admins);
if you wanted to accommodate for an array of different roles, you can use the following, easy to follow example.
var data = [{"visitor":{"static":["page-one:visit","home-page:visit","login"]}},{"users":{"static":["posts:list","posts:create","users:getSelf","home-page:visit","dashboard-page:visit"]}},{"admin":{"static":["posts:list","posts:create","posts:edit","posts:delete","users:get","users:getSelf","home-page:visit","dashboard-page:visit"]}}]
var role = ["admin", "visitor"];
var admins = role.map(function(role) { return getObjectsForRole(role); })
function getObjectsForRole(role)
{
return data.find(function(x){
return Object.keys(x).indexOf(role) > -1;
});
}
console.log(admins);
The above is pretty much the same as before, but we're mapping (.map) each role and calling a function which contains our call to the .find function.
With a javascript json object like this:
var data = {
blog : {
title: "my blog",
logo: "blah.jpg",
},
posts : [
{
title: "test post",
content: "<p>testing posts</p><br><p>some html</p>"
},
]
}
var lookup = "blog.title" //this gets generated from a template file
Now I know you can do something like, but these don't quite do what I need:
console.log(data['blog']); //works
console.log(data.blog.title); //works
console.log(data['blog']['title']); //works, but i dont know the depth of the lookup
But I need to be able to do something like the code below because I can't hardcode the structure, it gets generated and stored in lookup each time. Do I have to build this functionality using string cutting and recursion?? I really hope not
console.log(data['blog.title']); //does not work
console.log(data[lookup]); //does not work
EDIT....
Okay, possibly found a workaround. I don't know if this is safe or recommended practice, so comments on that would be great. Or alternative methods. So combining this with the code above.
var evaltest = "var asdf ="+JSON.stringify(data)+";\n"
evaltest += "asdf."+lookup
console.log(eval(evaltest)) //returns correctly "my blog" as expected
You could use dottie https://www.npmjs.org/package/dottie, which allows you to deep traverse an object using strings
var values = {
some: {
nested: {
key: 'foobar';
}
}
}
dottie.get(values, 'some.nested.key'); // returns 'foobar'
dottie.get(values, 'some.undefined.key'); // returns undefined
you could use:
data['blog']['title']
I've experimented with a couple ways of doing this including eval and using a dictionary lookup with switch(exp.length). This is the final version (comments stripped) I created:
var deepRead = function (data, expression) {
var exp = expression.split('.'), retVal;
do {
retVal = (retVal || data)[exp.shift()] || false;
} while (retVal !== false && exp.length);
return retVal || false;
};
//example usage
data = {
a1: { b1: "hello" },
a2: { b2: { c2: "world" } }
}
deepRead(data, "a1.b1") => "hello"
deepRead(data, "a2.b2.c2") => "world"
deepRead(data, "a1.b2") => false
deepRead(data, "a1.b2.c2.any.random.number.of.non-existant.properties") => false
Here's the Gist with full commenting: gist.github.com/jeff-mccoy/9700352. I use this to loop over several thousand items and have had no issues with deep-nested data. Also, I'm not wrapping in try/catch anymore due to the (small) performance hit: jsPerf.
Actually I want to search an attribute's value in an json array for one of its child. Now one condition is that the attribute will not be there in all the child's of the array. This is my json array.
[{
"heading1":"heading1",
"heading2":"heading2",
"heading3":"heading3",
"heading4":"heading4",
"heading5":"heading5",
"heading6":"heading6"
},
{
"column1":65536,
"column2":"school",
"column3":"testing purpose",
"column4":"DESKTOP",
"column5":"ACTIVE",
"column6":true,
"column7":"a6cc82e0-a8d8-49b8-af62-cf8ca042c8bb"
},
{
"column1":98305,
"column2":"Nikhil",
"column3":"Test",
"column4":"LAPTOP",
"column5":"ACTIVE",
"column6":true,
"column7":"a6cc82e0-a8d8-49b8-af62-cf8ca042c8bb"
}]
So presently I am working with the each loop but like this
var obj = $.parseJSON(JSON.stringify(response));
$.each(obj, function () {
console.log("heading1", this['heading1']);
});
Here response comes from mserver and it is the json array
Now I want to know can I search for this attribute in the json array without using a loop in jQuery.
Based on your sample code what I understand you have is an array of objects and you want to find objects with one specific property and or value:
This will return true if the object has the property
var results= arr.filter(function(item){ return item.hasOwnProperty("column5"); });
Or you can perform additional action when you find the property:
arr.filter(function(item){
if (item.hasOwnProperty("column5")) {
return item["column5"] === 'demo 01'; //or item.column5 === 'demo 01'
}
return false;
});
This only works on IE9+ if you need this to run in older versions of IE, please follow the instructions under polyfill:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/filter
The you can check like
var obj = $.parseJSON(response);
$.each(obj, function (index,value) {
if(typeof obj[index].heading2 !== "undefined")
{
alert(obj[index].heading2);
}
when in other object of array element not find then it returns undefined. and you can check like that.
you can check in this http://jsfiddle.net/gKRCH/
It's best to use a loop. But if the format of the JSON is regular, you could regex for the value in the response string.
I'm not recommending this method, just pointing out that it exists.
var value = "heading1";
if( (new RegExp('"' + value + '"')).test(response) ){
// Found value
};
Here, we take the required value, wrap it in quotation marks and search for it in the response.
This has several issues, such as:
It might find the pattern in a property name
If the value could contain regex special characters, they'll need escaping.
If your JSON contains values with escaped quotation marks, you could get a false positive from partial matches.
That's why it depends on you knowing the format of the data.
EDIT:
You can solve issue 2 by using this condition instead of regex. But it gives you less flexibility.
response.indexOf('"' + value + '"') !== -1
Try this,
$.each(object,function(key, value){
console.log(key);
console.log(value);
});
You can use this JS lib; DefiantJS (http://defiantjs.com). This lib extends the global object JSON with the method "search" - with which, you can perform XPath queries on JSON structures. Like the one you have exemplified.
With XPath expressions (which is standardised query language), you can find whatever you're looking for and DefiantJS will do the heavy-lifting for you - allowing your code to be neat and clean.
Here is the fiddle of this code:
http://jsfiddle.net/hbi99/q8xst/
Here is the code:
var data = [
{
"heading1": "heading1",
"heading2": "heading2",
"heading3": "heading3",
"heading4": "heading4",
"heading5": "heading5",
"heading6": "heading6"
},
{
"column1": 65536,
"column2": "school",
"column3": "testing purpose",
"column4": "DESKTOP",
"column5": "ACTIVE",
"column6": true,
"column7": "a6cc82e0-a8d8-49b8-af62-cf8ca042c8bb"
},
{
"column1": 98305,
"column2": "Nikhil",
"column3": "Test",
"column4": "LAPTOP",
"column5": "ACTIVE",
"column6": true,
"column7": "a6cc82e0-a8d8-49b8-af62-cf8ca042c8bb"
}
],
res = JSON.search( data, '//*[column4="DESKTOP"]' );
console.log( res[0].column2 );
// school