Accessing elements of JSON object without knowing the key names - javascript

Here's my json:
{"d":{"key1":"value1",
"key2":"value2"}}
Is there any way of accessing the keys and values (in javascript) in this array without knowing what the keys are?
The reason my json is structured like this is that the webmethod that I'm calling via jquery is returning a dictionary. If it's impossible to work with the above, what do I need to change about the way I'm returning the data?
Here's an outline of my webmethod:
<WebMethod()> _
Public Function Foo(ByVal Input As String) As Dictionary(Of String, String)
Dim Results As New Dictionary(Of String, String)
'code that does stuff
Results.Add(key,value)
Return Results
End Function

You can use the for..in construct to iterate through arbitrary properties of your object:
for (var key in obj.d) {
console.log("Key: " + key);
console.log("Value: " + obj.d[key]);
}

Is this what you're looking for?
var data;
for (var key in data) {
var value = data[key];
alert(key + ", " + value);
}

{
"d":{
"key1":"value1",
"key2":"value2"
}
}
To access first key write:
let firstKey=Object.keys(d)[0];
To access value of first key write:
let firstValue= d[firstKey];

By using word "b", You are still using key name.
var info = {
"fname": "Bhaumik",
"lname": "Mehta",
"Age": "34",
"favcolor": {"color1":"Gray", "color2":"Black", "color3":"Blue"}
};
Look at the below snippet.
for(key in info) {
var infoJSON = info[key];
console.log(infoJSON);
}
Result would be,
Bhaumik
Mehta
Object {color1: "Gray", color2: "Black", color3: "Blue"}
Don’t want that last line to show up? Try following code:
for(key in info) {
var infoJSON = info[key];
if(typeof infoJSON !== "object"){
console.log(infoJSON);
}
}
This will eliminate Object {color1: “Gray”, color2: “Black”, color3: “Blue”} from showing up in the console.
Now we need to iterate through the variable infoJSON to get array value. Look at the following whole peace of code.
for(key in info) {
var infoJSON = info[key];
if (typeof infoJSON !== "object"){
console.log(infoJSON);
}
}
for(key1 in infoJSON) {
if (infoJSON.hasOwnProperty(key1)) {
if(infoJSON[key1] instanceof Array) {
for(var i=0;i<infoJSON[key1].length;i++) {
console.log(infoJSON[key1][i]);
}
} else {console.log(infoJSON[key1]);}
}
}
And now we got the result as
Bhaumik
Mehta
Gray
Black
Blue
If we use key name or id then it’s very easy to get the values from the JSON object but here we are getting our values without using key name or id.

Use for loop to achieve the same.
var dlist = { country: [ 'ENGLAND' ], name: [ 'CROSBY' ] }
for(var key in dlist){
var keyjson = dlist[key];
console.log(keyjson)
}

Related

Nested Json Access Value

Here is my Json-String:
{
"batchcomplete":"",
"query":{
"pages":{
"104352":{
"pageid":104352,
"ns":0,
"title":"student"
}
}
}
}
I want to access tha first number, in this example "103452", not the on after pageid, although they always should be the same.
I tried the following until know, but don´t get why it wont work.
JSONName.query.pages;
it always returns me Object object.
Assuming you have a JavaScript object you can get the keys of an object which would contain your string.
const obj = {
"batchcomplete": "",
"query": {
"pages": {
"104352": {
"pageid": 104352,
"ns": 0,
"title": "student"
}
}
}
}
// Get the keys for pages
const keys = Object.keys(obj.query.pages);
// Print out the first key
console.log(keys[0]);
Might be easier to find it during the parsing:
var n, j = '{"batchcomplete":"","query":{"pages":{"104352":{"pageid":104352,"ns":0,"title":"student"}}}}';
var result = JSON.parse(j, (key, value) => (n = n || +key, value));
console.log( n ); console.log( result );

Getting child data in a JavaScript object

I have been banging my head against this all night.
I have a service that is returning data that looks like this:
You will see there are Objects with a GUID, nested under a parent object. I need to loop through all the "GUID" objects and get the attributes (i.e., author, content, etc.).
The GUIDs are dynamic (I don't know what they are ahead of time). The attributes below it are known.
I am having trouble figuring out how to target it. I can't seem to successfully use a for or forEach loop on it.
I need to use native JavaScript (i.e. no jQuery for this one).
Here's a possible solution:
var keys = Object.keys(data);
var results =
keys.map(
function(key){
var datum = data[key];
// do whatever with the data.
return {
"author" : data["author"]
}
}
)
// now results is an array of {"author"} objects.
var x = {
'a-45-2455': {
'author': 'Some Name'
}
};
var keys = Object.keys(x);
keys.forEach(function(key,value){
var author = x[key]['author'];
console.log(author);
});
You can access the data in this way.
You can also create another array from the values and use that.
In order to loop through an object use for...in
Since you have not posted the code of object , here is a snippet with dummy object
var x = {
'a-45-2455': {
'author': 'Some Name'
}
}
for(var keys in x){
alert(x[keys].author)
}
If you are using angular try angular.forEach loop to iterate over all GUID's, else you can use for each in javascript. see below code snippet.
var user ={
'1': {
"name":'abc',
"age":26
},
'2': {
"name":'def',
"age":28
}
};
for(var key in user) {
console.log(user[key].name);
}
Here is another way to iterate through json Object
var obj = {a: 1, b: 2, c: {a: 1, b: 2}};
function walk(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
console.log(val);
walk(val);
}
}
}
walk(obj);
var obj = {a: 1, b: 2, c: {a: 1, b: 2}};
function walk(obj) {
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
var val = obj[key];
console.log(val);
walk(val);
}
}
}
walk(obj);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
I believe that you can iterate through all indexes using the advanced for loop. a.b is the same as a["b"] in javascript.
You can iterate thru the object properties like this:
for(let key in Response){
if(!Response.hasOwnProperty(key))
continue;
//key will be each GUID
let yourObject = Response[key] //Each object in the list of objects
}
You can read about for...in loops here
Hope that helps!

Javascript, how to split key with dot to recovery json structure

I have a json, it is
{
"prop1.sub1.sub2": "content1",
"prop1.sub1.sub3": "content2",
"prop2.sub1.sub2": "content3",
"prop3.sub1.sub2": "content4"
}
I want to recovery the structure, like
{
"prop1": {
"sub1": {
"sub2" : "content1",
"sub3" : "content2"
}
},
"prop2": {
"sub1": {
"sub2" : "content3"
}
},
"prop3": {
"sub1": {
"sub2" : "content4"
}
}
}
I split the key with dot to get each key.
for (var key in json) {
var keySplit = key.split('.');
// Todo: recovery the structure
}
But not found a good solution.
Is anyone has solution?
You can use Array#reduce method.
var obj = {
"prop1.sub1.sub2": "content1",
"prop1.sub1.sub3": "content2",
"prop2.sub1.sub2": "content3",
"prop3.sub1.sub2": "content4"
};
// iterate over the property names
Object.keys(obj).forEach(function(k) {
// slip the property value based on `.`
var prop = k.split('.');
// get the last value fom array
var last = prop.pop();
// iterate over the remaining array value
// and define the object if not already defined
prop.reduce(function(o, key) {
// define the object if not defined and return
return o[key] = o[key] || {};
// set initial value as object
// and set the property value
}, obj)[last] = obj[k];
// delete the original property from object
delete obj[k];
});
console.log(obj);
Answer by Pranav C Balan is right for the question you asked. But JSON's might not be as simple as you have mentioned above and can have array's also and few keys might not have "." in them. To handle all these cases you can use the following one.
var obj = {
"prop1.sub1.sub2": "content1",
"prop1.sub1.sub3": "content2",
"prop2.sub1.sub2": "content3",
"prop3.0.sub2": "content4"
};
function createJSONStructure(obj) {
Object.keys(obj).forEach(function(k) {
var prop = k.split('.'); //split on . to get elements
if(prop.length >1){ //If there is no dot just key the value as is.
let data = obj;//Copy the default object to data in each loop
for(i=0;i<prop.length-1;i++){
if(data[prop[i]]){ // Check if the key exists
if((prop[i+1].match(/^\d+$/) && !Array.isArray(data[prop[i]])) // Check if the next key is a digit and the object we have is a JSON
|| (!prop[i+1].match(/^\d+$/) && Array.isArray(data[prop[i]]))){ // Check if the next key is not a digit and the object we have is a Array
throw new Error("Invalid header data"); //If any of the above cases satisfy we cannot add the key so we can throw an error.
}
data = data[prop[i]]; // If key exisits make the data variable as the value of the key
}else {
if(prop[i+1].match(/^\d+$/)){ //If the key is not available see if the next parameter is a digit or string to decide if its array or string
data[prop[i]] = [];
}else{
data[prop[i]] = {};
}
data = data[prop[i]]; //Assign this new object to data
}
};
data[prop[i]] = obj[k]; //Finally add the value to final key
delete obj[k]; // delete the exisiting key value
}
});
return obj;
}
console.log(createJSONStructure(obj));

How to iterate through whole json in javascript

I can have a json object. This object is not the same everytime. It can change dynamically. It can have object of arrays, array of arrays, array of objects anything that follows http://www.json.org/ standard
I want to XML escape each of the leaf level json object.
var jsonObject = {};//is not standard will change dynamically
var xmlescape = require('xml-escape');
iterate through each of the json object
jsonObjectAtParticularLevel = xmlescape(jsonObjectAtParticulatLevel);
How do I iterate through the whole json object and change it?
I tried to use JSON.stringify and JSON.parse, but I don't think that would be efficient.
function replacer(key, value) {
if (typeof value === "string") {
return xmlescape(value);
}
return value;
}
var newJsonObject = JSON.parse(JSON.stringify(jsonObject, replacer));
I want to use something like a recursive loop which will iterate through the whole json. But I'm able to figure out how to parse the whole json.
JSON.parse with revival function should be enough
var object = {"id":"10", "class": [{"child-of-9": "AABC"}, {"9": "a"}]};
$(function() {
object = JSON.parse(JSON.stringify(object), function (k, v) {
if(typeof v == "string") {
return v + "changed";
}
return v;
})
console.log(JSON.stringify(object));
alert(JSON.stringify(object));
});
let obj = {
'name': '',
'age' : ''
}
Object.keys(obj).forEach(key => {
console.log(key, '--> List of keys in the object')
})

Retrieve property value from array literal

I keep getting eluded by how property values should be properly retrieved from array literals.
Object literal:
var obj = {
"p1": "v1",
"p2": "v2",
"p3": "v3"
};
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
console.log(key + " -> " + obj[key]);
}
}
Console log output:
p1 -> v1
p2 -> v2
p3 -> v3
Array literal:
var obj = [
{ "pa":"va1", "pb":"vb1" },
{ "pa":"va2", "pb":"vb2" },
{ "pa":"va3", "pb":"vb3" },
{ "pa":"va4", "pb":"vb4" }
];
for (var key in obj) {
if (obj.hasOwnProperty(key)) {
console.log(key + " -> " + obj[key]);
}
}
Console log output (duh!):
0 -> [object Object]
1 -> [object Object]
2 -> [object Object]
3 -> [object Object]
What I'm trying to do: check if a string matches one of the pa values. If it does, do something.
This would be the logic:
var myString = "a value I'm getting from somewhere else ;)"
if (myString == any of the pa values) {
// do something
}
Any help appreciated!
Using the filter method (link contains code to add functionality to older browsers - IE8 and older) and then check the length of the resulting array:
var obj = [
{ "pa":"va1", "pb":"vb1" },
{ "pa":"va2", "pb":"vb2" },
{ "pa":"va3", "pb":"vb3" },
{ "pa":"va4", "pb":"vb4" }
];
var filtered = obj.filter(function(element) {
return element.pa === myString;
});
if (filtered.length > 0) {
// contains string
}
JS Fiddle
obj is not a object as you expect, it's an array of objects. You'll need to iterate the array and then iterate the keys in each array item.
var i, key;
for (i = 0; i < obj.length; i++) {
for (key in obj[i]) {
if (obj[i].hasOwnProperty(key) {
console.log(key + " -> " + obj[i][key]);
}
}
}
If you don't need to know the parent, there may be a performance boost in not looping through it all (depending on array and object sizes). This will also remove the need to change your code if another nested level of objects is added.
JSON.stringify(obj).indexOf(':"pa1"')>-1
JSON.stringify() turns your array into a string like this:
"[{"pa":"va1","pb":"vb1"},{"pa":"va2","pb":"vb2"},{"pa":"va3","pb":"vb3"},{"pa":"va4","pb":"vb4"}]"
Which we can then of course just do a normal textual search through
JSON.stringify() is supported for IE8 and above
This may be oversimplifying, but if you just want to know if you have a string in mystring that is an item in the array, the array can be addressed as indexed by strings.
Update - I ran this through firebug and discovered I had my notation incorrect for this method to work the way I thought it should - namely as a referable list of objects or values by label.
var obj = [];
obj["val1"] = "pa";
obj["val2"] = "pb";
mystring="val1";
if (obj[mystring]){
alert ('object exists in array');
}
else{
alert('object with index ' + mystring + ' does not exist');
}
No looping required, though your array setup has to change to support this sort of "look up" approach.

Categories