This might be a silly question but I did not found any answers for it. How can I get the parent's name from this json for example ?
{
"someParentName":{
"somechild":{
"value1":"test"
}
}
}
So how can i log the "someParentName" ? Any language would be good but i am using JS.
var data = {
"someParentName":{
"somechild":{
"value1":"test"
}
}
}
var parent_key = Object.keys(data)[0]
console.log(data[parent_key]);
Right now it's not a JSON, it's already an object. That's fine. The Object.keys method will give you all the top-level property names (so, here, ["someParentName"]). Is this what you're after?
const obj = {
"someParentName": {
"somechild": {
"value1": "test"
}
}
}
console.log(Object.keys(obj));
If your object has a single key, then you can use Object.keys(obj)[0], otherwise, using Object.keys() will return an array of all keys at root level:
const obj = {
"someParentName":{
"somechild":{
"value1":"test"
}
}
}
console.log(Object.keys(obj)[0]);
Try this:
console.log(data.someParentName.somechild.value1);
where
var data = {
"someParentName":{
"somechild":{
"value1":"test"
}
}
}
there was a lot of these on stackoverflow
How to access elements of json array using javascript/jquery? [closed]
Related
If I have a JSON object like this:
{
"message": {
"name": { "stringLengthTooShort": "blub" }
}
}
The name of the property (here) stringLengthTooShort is changing every time,
how could I simply just get the child property of name with JS?
At the moment I have message.name but how could I get now the child of it?
if it's always the first property of message.name, you could do something like:
var keys = [];
for (var l in message.name) {
if (message.name.hasOwnProperty(l)){
keys.push(l);
}
}
//=>first property value should now be in message.name[keys[0]]);
// (its label is keys[0])
Edit: nine years after this answer all modern browsers support es20xx, so it's safe to use:
const obj = {
"message": {
"name": { "stringLengthTooShort": "blub" }
}
};
console.log(Object.keys(obj.message.name)[0]);
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;
}
This is my object that contains 3 objects.
{
"costco":
{
"costco_11":{"id":1, "address":"123 main"},
"costco_12":{"id":2, "address":"345 Oak"},
"costco_13":{"id":3, "address":"789 Birch"}
}
}
I would like to create a single array that contains 3 objects so that I can dynamically create some ListView items in React-Native.
I would like to avoid using Lodash(Probably not needed, but I just want to make sure since I mentioned react-native)
I would like to create a single array that contains 3 objects
Simply get Object.values
var obj = {
"costco":{
"costco_11":{"id":1, "address":"123 main"},
"costco_12":{"id":2, "address":"345 Oak"},
"costco_13":{"id":3, "address":"789 Birch"}
}
};
obj.costco = Object.values(obj.costco);
console.log(obj);
There is no need for external libs; you can do it in plain Javascript.
let myObj = {"costco":{
"costco_11":{"id":1, "address":"123 main"},
"costco_12":{"id":2, "address":"345 Oak"},
"costco_13":{"id":3, "address":"789 Birch"}
}
};
let myArray = Object.values(myObj.costco);
I made a little fiddle for this.
const newArr = Object.keys(fakeOb).map(function(k) { return fakeOb[k]});
console.log(newArr);
I am trying to wrap my head around how I might accomplish something like this, structurally:
var keywordDataProducts =
[
{"keyword" : "keyword1", "list" : [ "DP1", "DP2" ] },
{"keyword" : "keyword2", "list" : [ "DP1" ] }
];
But of course, without the values being hard coded. For instance, we currently loop through all the DP values (DP1, DP2, DP3, etc..) - which all have 0-M keywords. I'm trying to create an inverse lookup of that, where you can get all DPs that use a particular keyword. I have code that uses the structure above perfectly, but I just need the data to get populated more dynamically.
Do I initialize the var keywordDataProducts = []; declaration with anything in it, or define the structure of it having a keyword and a list (which is an array)? Or do you leave it as an array with nothing about it, and define that when you're adding items?
I've heard associative arrays can be used for a situation like this, but I'm not quite wrapping my head around that at the moment. I've also seen objects with {} usages, but there is no push there and I need an array of keywords, which also contains arrays of DPs (list). Thoughts?
You would do something like this, but you didn't clearly describe what the input look like and what output you're looking for.
function fn (input) {
var ouput = {};
input.forEach( function (DP) {
for (prop in DP) {
if (DP.hasOwnProperty(prop) {
if (output[prop]) {
output[prop].push(DP);
} else {
output[prop] = [DP];
}
}
}
});
return output;
}
This takes this kind of input
[{"alpha":...}, {"beta":..., "delta":...}, {"alpha":..., "gamma":...}]
and returns
{"alpha":[{"alpha":...}, {"alpha":..., "gamma":...}]}, "beta":{"beta":..., "delta":...}, "delta":{"beta":..., "delta":...}, "gamma":{"alpha":..., "gamma":...}}
I don't know how you want your output so I just made an object with each keyword as its own key for the DP values.
var data = [{dp: "dp1", keys: ["key1", "key2", "key3"]}, {dp: "dp2", keys: ["key1", "key2", "key3"]}, {dp: "dp3", keys: ["key1", "key2", "key3"]},];
function keyWordArray(arr) {
var newObj = {};
arr.forEach((obj) => {
obj.keys.forEach((keyVal) => {
if(newObj.hasOwnProperty(keyVal)){
newObj[keyVal].dp.push(obj.dp);
} else {
newObj[keyVal] = {dp:[obj.dp],};
}
});
});
return newObj;
}
document.getElementById("data").innerHTML = JSON.stringify(keyWordArray(data));
<div id="data">
</div>
You can treat objects as associative arrays, and you don't have to use "push" to add a new element.
// Create your object like this
var keywordDataProducts =
{
"keyword1" : { "list" : [ "DP1", "DP2"] },
"keyword2" : { "list" : [ "DP1" ] }
};
// Treat it like an associative array
var keyword1 = keywordDataProducts["keyword1"];
alert("keyword1 = " + keyword1.list.join(", "));
// Add to it like this
keywordDataProducts["keyword3"] = { "list" : ["DP3", "DP4"] };
// See the new object includes your new keyword
alert(JSON.stringify(keywordDataProducts));
// To iterate the keys of your object, you can do something like this
for(var item in keywordDataProducts)
{
if(keywordDataProducts.hasOwnProperty(item))
{
alert(item);
}
}
You can see the fiddle here;
https://jsfiddle.net/gksjtwr6/2/
I have two object JSON which having hierachical structure. I need to compare each object inside rowset in JSON. And where ever the value not gettng equal
then i have to addd one flag on corresponding object.
Please hava a look at my JSONs and give solution for that. If not angular atleast i have to achieve in Javascript.
Thanks in advance...
JSON1
{"entityinfo":{"entity":"Customer29Jan16","tenantid":"292FEC76-5F1C-486F-85A5-09D88096F098","timestamp":"2015-12-15T10:16:06.322Z"},"collections":{"Customer29Jan16":{"rowset":[{"CuId":"123","Name":"Ranjini","Quantity":"60","Rate":"60","Amount":"3600"}],"meta":{"parentreference":"***","pkname":"***","fkname":"***"},"rowfilter":[]},"Customer29Jan16Obj":{"rowset":[{"CuObjId":"456","FullAddress":"Electronic City","ObjAddr":"Bangalore","ObjName":"Testing"}],"meta":{"parentreference":"***","pkname":"***","fkname":"***"},"rowfilter":[]}}}
JSON2
{"entityinfo":{"entity":"Customer29Jan16","tenantid":"292FEC76-5F1C-486F-85A5-09D88096F098","timestamp":"2015-12-15T10:16:06.322Z"},"collections":{"Customer29Jan16":{"rowset":[{"CuId":"123","Name":"Vijay","Quantity":"60","Rate":"60","Amount":"3600"}],"meta":{"parentreference":"***","pkname":"***","fkname":"***"},"rowfilter":[]},"Customer29Jan16Obj":{"rowset":[{"CuObjId":"456","FullAddress":"SilkBoard","ObjAddr":"Bangalore","ObjName":"Testing"}],"meta":{"parentreference":"***","pkname":"***","fkname":"***"},"rowfilter":[]}}}
Use angular.equals(o1,o2) . It does deep comparison and does not depend on the order of the keys
angular.equals(JSON1, JSON2); // return boolean (true or false) based on the comparison
refer : Angularjs Docs
I've made an starting example for you to build on. You can play with it here.
JavaScript
var json1 = {"entityinfo":{"entity":"Customer29Jan16","tenantid":"292FEC76-5F1C-486F-85A5-09D88096F098","timestamp":"2015-12-15T10:16:06.322Z"},"collections":{"Customer29Jan16":{"rowset":[{"CuId":"123","Name":"Ranjini","Quantity":"60","Rate":"60","Amount":"3600"}],"meta":{"parentreference":"***","pkname":"***","fkname":"***"},"rowfilter":[]},"Customer29Jan16Obj":{"rowset":[{"CuObjId":"456","FullAddress":"Electronic City","ObjAddr":"Bangalore","ObjName":"Testing"}],"meta":{"parentreference":"***","pkname":"***","fkname":"***"},"rowfilter":[]}}};
var json2 = {"entityinfo":{"entity":"Customer29Jan16","tenantid":"292FEC76-5F1C-486F-85A5-09D88096F098","timestamp":"2015-12-15T10:16:06.322Z"},"collections":{"Customer29Jan16":{"rowset":[{"CuId":"123","Name":"Vijay","Quantity":"60","Rate":"60","Amount":"3600"}],"meta":{"parentreference":"***","pkname":"***","fkname":"***"},"rowfilter":[]},"Customer29Jan16Obj":{"rowset":[{"CuObjId":"456","FullAddress":"SilkBoard","ObjAddr":"Bangalore","ObjName":"Testing"}],"meta":{"parentreference":"***","pkname":"***","fkname":"***"},"rowfilter":[]}}};
function compareJSON(json1, json2) {
var objectsDiffering = [];
compareJSONRecursive(json1, json2, objectsDiffering);
return objectsDiffering;
}
function compareJSONRecursive(json1, json2, objectsDiffering) {
for(prop in json1) {
if(json2.hasOwnProperty(prop)) {
switch(typeof(json1[prop])) {
case "object":
compareJSONRecursive(json1[prop], json2[prop], objectsDiffering);
break;
default:
if(json1[prop] !== json2[prop]) {
objectsDiffering.push(json1);
}
break;
}
}
else {
objectsDiffering.push(json1);
break;
}
}
}
var differing = compareJSON(json1, json2);
console.log(JSON.stringify(differing));
//Logs: [{"CuId":"123","Name":"Ranjini","Quantity":"60","Rate":"60","Amount":"3600"},{"CuObjId":"456","FullAddress":"Electronic City","ObjAddr":"Bangalore","ObjName":"Testing"}]