How read of Object.keys() value JSON? - javascript

How read of Object.keys() value JSON ?
I trying read value key name, but give error:
Keys dynamic
{
"marka1": {
"name": "Mika",
},
"beti1": {
"name": "Yii",
}
}
var ojson = JSON.parse(objectJson);
var keys = Object.keys(ojson); //read good key
console.log("test - " + ojson.keys[0].name); //give error

Change it to console.log("test - " + ojson[ keys[0] ].name); because keys[0] is just a string.

Related

Iterating over a json array whose key value is dynamic

I have a json structure as:
{
"TestCaseList": [
{
"TC_1": {
"name":"verifyloginpagedetails",
"value":"2"
},
"TC_2": {
"name":"verify registration page details",
"value":"3"
}
}
],
"Summary": {
"v":[
{
"name":"over the ear headphones - white/purple",
"value":1
}
]
}
}
How to extract the values name, value of TC_1 , TC_2 where TC_1 is dynamic i.e. key of TestCaseList?
You can use the Object.keys method to get an array of the keys of an object.
With a single object in the array at "TestCaseList" in your JSON object, this will work:
// jsonObj is your JSON
testCaseKeys = Object.keys(jsonObj.TestCaseList[0]);
If, however, the array at "TestCaseList" contains more than one one element, you can use this to get each set of keys in an individual array:
testCaseKeySets = jsonObj.TestCaseList.map(obj => Object.keys(obj));
I'm sure a more elegant solution exists, but this will do the trick.
var myObj = {
"TestCaseList":
[{
"TC_1":
{"name":"verifyloginpagedetails",
"value":"2"},
"TC_2":
{"name":"verify registration page details",
"value":"3"}
}],
"Summary":{
"v":[{"name":"over the ear headphones - white/purple","value":1}]
}
}
let testCaseListKeys = Object.keys(myObj.TestCaseList[0]);
for(i=0; i < testCaseListKeys.length; i++){
let tclKey = testCaseListKeys[i];
console.log(tclKey + "\'s name = " + myObj.TestCaseList[0][tclKey].name);
console.log(tclKey + "\'s value = " + myObj.TestCaseList[0][tclKey].value);
}
The console.logs are your output. The important values there are the myObj.TestCaseList[0][tclKey].name and the myObj.TestCaseList[0][tclKey].value
** UPDATE **
After answering the question Ananya asked how to do this same thing if the object had a different structure.
Updated Object:
var myObj2 = {
"TestCaseList":
[{
"TC_1":{
"name":"verifyloginpagedetails",
"value":"2"}
},
{
"TC_2":{
"name":"verify registration page details",
"value":"3" }
}],
"Summary":
{
"v":[ {"name":"over the ear headphones - white/purple","value":1} ]
}
}
Updated JavaScript:
for(x=0;x<myObj2.TestCaseList.length;x++) {
let testCaseListKeys = Object.keys(myObj2.TestCaseList[x]);
for(i=0; i < testCaseListKeys.length; i++){
let tclKey = testCaseListKeys[i];
//console.log(tclKey);
console.log(tclKey + "\'s name = " + myObj2.TestCaseList[x][tclKey].name);
console.log(tclKey + "\'s value = " + myObj2.TestCaseList[x][tclKey].value);
}
}

How to iterate over json with no name

var categories= {
"art": 352,
"health-beauty": 358,
"home": 372,
"jewelry": 339,
"kids": 320
}
for(var i in categories)
{
console.log("name: " + i + "id: " + ?);
}
I'm trying to import name of categories and id to mongodb but having hard time how to get the ID of each value? Is this possible or I have to re arrange the JSON file by hand?
Your var i contains the property and object's properties can be accessed using an arraylike notation. so:
for(var i in categories) {
console.log("name: " + i + "id: " + categories[i]);
}
I recommend that you always put your curly braces on the right because not doing so would yield unexpected results:
function someFunction ()
{
return
{
prop: "Prop"
}
}
alert(someFunction().prop); // Error, it returned undefined because something called semi-colon insertion. Read about it.

different javascript object keys seem to be evaluated as being the same

I'm using an object as a map and storing objects in it using the pattern map[obj.href] = obj
I'm expecting duplicate keys, but something really weird is happening:
I have 2 completely different (every field) objects stored with different keys, but when a 3rd object has the same key as 1st, a lookup is returning the 2nd object (stored with a different key), and when I do a lookup of the returned object's href, I get that same object again, as if the 2 keys are equivalent.
According to Which characters are valid/invalid in a JSON key name? and some other posts on SO, any valid string can be a key in an object, and you don't need to escape any characters, which I was worried about because of all the '/'s and '#'s.
I'm sureit's just a simple bug in my code, which I can't see it because it's 8 am and I have been up all night. Any help spotting it would be appreciated.
function parseSpellsList($)
{
var spellsList = {};
$("ul[class|='link'],ul[class$='level']").each(function() {
var obj, spell_type, links, i, link, a, span, prevObj, hashKey;
obj = {};
links = this.children;
for (i=0; i<links.length; i++) {
link = links[i];
a = link.children[0];
obj.href = a.href.replace("file:///home/ckot/rpg_app/", "").replace("scripts/", "");
obj.name = a.innerHTML.replace("<b>", "").replace("</b>", "");
hashKey = obj.href;
prevObj = null;
if ( !(spellsList.hasOwnProperty(hashKey))) {
// debug code
if ("Blood Blaze" === obj.name || "Vomit Swarm" === obj.name) {
console.log("storing " + JSON.stringify(obj, null, " ") + " with hashKey: " + hashKey);
}
spellsList[hashKey] = obj;
} else {
console.log("\nWARNING: hashKey " + hashKey + " already exists");
prevObj = spellsList[hashKey];
console.log("object we which to store with hashKey: " + hashKey + "\n" + JSON.stringify(obj, null, " ")) ;
console.log("object retrieved with hashKey: " + hashKey + "\n" + JSON.stringify(prevObj, null, " "));
console.log("object retrieved with hashKey: " + prevObj.href + "\n" + JSON.stringify(spellsList[prevObj.href], null, " ") + "\n");
}
}
});
}
when I run it I get the following output:
storing {
"href": "advancedRaceGuide/featuredRaces/orcs.html#blood-blaze",
"name": "Blood Blaze"
} with hashKey: advancedRaceGuide/featuredRaces/orcs.html#blood-blaze
storing {
"href": "advanced/spells/vomitSwarm.html#vomit-swarm",
"name": "Vomit Swarm"
} with hashKey: advanced/spells/vomitSwarm.html#vomit-swarm
WARNING: hashKey advancedRaceGuide/featuredRaces/orcs.html#blood-blaze already exists
object we which to store with hashKey: advancedRaceGuide/featuredRaces/orcs.html#blood-blaze
{
"href": "advancedRaceGuide/featuredRaces/orcs.html#blood-blaze",
"name": "Blood Blaze"
}
object retrieved with hashKey: advancedRaceGuide/featuredRaces/orcs.html#blood-blaze
{
"href": "advanced/spells/vomitSwarm.html#vomit-swarm",
"name": "Vomit Swarm"
}
object retrieved with hashKey: advanced/spells/vomitSwarm.html#vomit-swarm
{
"href": "advanced/spells/vomitSwarm.html#vomit-swarm",
"name": "Vomit Swarm"
}
EDIT:
just for some context I'm using:
node v0.10.22
npm v1.4.24
and the npm modules:
jsdom v1.0.0-pre.3
jquery v2.1.1",
nvm, I was initializing obj at the start of $.each() instead of inside the nested for loop. :(
i guess I just need to get some sleep.

How to extract values from json using JSON.parse

I am having the following code:
data = JSON.stringify({
"result": [
{
"username": "username should not empty"
},
{
"password": "password should not empty"
}
],
"validate_flag": 1
})
data = JSON.parse(data);
$.each(data,function(index,value){
console.log(index);
console.log(value);
});
console.log(data);
Here I can extract the second key "validate_flag" directly using $.each. But when I tried to extract "result" I got two objects. Now,how can I effectively use $.each() to extract the following json regardless of multi-dimensional or single-dimensional. Also how can I access object in the key value "username" and "password"? Here is the link for fiddle I tried?
Try this: http://jsfiddle.net/zds6M/3/
var echoOut = function(data){
$.each(data,function(i,v){
if(typeof v == 'object'){
console.log('In: ' + i);
echoOut(v);
}else{
console.log(i + ': ' + v);
}
});
};
data = JSON.parse(data);
echoOut(data);
properties of an object in javascript can be accessed via
for in loop
for (var x in yourobject)
{
// key is x
// value is object[x]
}
if you already know the property name
than use can use yourobject["propertyname"] or yourobject.propertyname

Use a JSON array with objects with javascript

I have a function that will get a JSON array with objects. In the function I will be able to loop through the array, access a property and use that property. Like this:
Variable that I will pass to the function will look like this:
[{
"id": 28,
"Title": "Sweden"
}, {
"id": 56,
"Title": "USA"
}, {
"id": 89,
"Title": "England"
}]
function test(myJSON) {
// maybe parse my the JSON variable?
// and then I want to loop through it and access my IDs and my titles
}
Any suggestions how I can solve it?
This isn't a single JSON object. You have an array of JSON objects. You need to loop over array first and then access each object. Maybe the following kickoff example is helpful:
var arrayOfObjects = [{
"id": 28,
"Title": "Sweden"
}, {
"id": 56,
"Title": "USA"
}, {
"id": 89,
"Title": "England"
}];
for (var i = 0; i < arrayOfObjects.length; i++) {
var object = arrayOfObjects[i];
for (var property in object) {
alert('item ' + i + ': ' + property + '=' + object[property]);
}
// If property names are known beforehand, you can also just do e.g.
// alert(object.id + ',' + object.Title);
}
If the array of JSON objects is actually passed in as a plain vanilla string, then you would indeed need eval() here.
var string = '[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]';
var arrayOfObjects = eval(string);
// ...
To learn more about JSON, check MDN web docs: Working with JSON
.
This is your dataArray:
[
{
"id":28,
"Title":"Sweden"
},
{
"id":56,
"Title":"USA"
},
{
"id":89,
"Title":"England"
}
]
Then parseJson can be used:
$(jQuery.parseJSON(JSON.stringify(dataArray))).each(function() {
var ID = this.id;
var TITLE = this.Title;
});
By 'JSON array containing objects' I guess you mean a string containing JSON?
If so you can use the safe var myArray = JSON.parse(myJSON) method (either native or included using JSON2), or the usafe var myArray = eval("(" + myJSON + ")"). eval should normally be avoided, but if you are certain that the content is safe, then there is no problem.
After that you just iterate over the array as normal.
for (var i = 0; i < myArray.length; i++) {
alert(myArray[i].Title);
}
Your question feels a little incomplete, but I think what you're looking for is a way of making your JSON accessible to your code:
if you have the JSON string as above then you'd just need to do this
var jsonObj = eval('[{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}]');
then you can access these vars with something like jsonObj[0].id etc
Let me know if that's not what you were getting at and I'll try to help.
M
#Swapnil Godambe
It works for me if JSON.stringfy is removed.
That is:
$(jQuery.parseJSON(dataArray)).each(function() {
var ID = this.id;
var TITLE = this.Title;
});
var datas = [{"id":28,"Title":"Sweden"}, {"id":56,"Title":"USA"}, {"id":89,"Title":"England"}];
document.writeln("<table border = '1' width = 100 >");
document.writeln("<tr><td>No Id</td><td>Title</td></tr>");
for(var i=0;i<datas.length;i++){
document.writeln("<tr><td>"+datas[i].id+"</td><td>"+datas[i].Title+"</td></tr>");
}
document.writeln("</table>");

Categories