How to fetch value from keys in JSON object? - javascript

I want to print all the key value pairs of a JSON object.
I don't know the keys of the object, so I am trying to get all the keys and corresponding values in a loop.
But it appears that I am missing something obvious.
My perl code
%some_data = ("key1" => "value1","key2" => "value2","key3" => "value3","key4" => "value4");
my $json = encode_json \%some_data;
print $json; # it prints {"key2":"value2","key4":"value4","key1":"value1","key3":"value3"}
my simple javascript code
var jsonObj=$json;
var keys= Object.keys(jsonObj);
for (var i = 0; i < keys.length; i++){
document.write("<br /> ");
document.write(keys[i]);
// document.write(jsonObj.[keys[i]]); # doesnt work
}
document.write(jsonObj.key1); #works

Just use for..in to loop an object:
for (var key in jsonObj) {
document.write(key);
document.write(jsonObj[key]);
}

You can't retrieve the value associated with a JavaScript object key by performing jsonObj.[keys[i]]. You should change that line to say jsonObj[keys[i]]. The dot notation will only work for a key that exists in the object. Since [keys[i]] is not actually a property of that object, you cannot use dot notation and must instead use square-bracket notation.

Your "doesn't work" line should be:
document.write(jsonObj[keys[i]]);
^--- no "."

You're combining the square-bracket notation (jsonObj[keys[i]]) and the dot notation (jsonObj.key1) when attempting to call document.write(); they're equivalent to each other so you should only be using one of them. In this case, since the key is dynamic, you should only be using the square bracket notation:
document.write(jsonObj[keys[i]]);

Related

Bad character in json response angular 2

I've retrieved a JSON response from an external API and one of the variable names begins with a # character, so the JSON variable looks like this #text. Unfortunately angular doesn't know how to handle this variable, is there any way delete the # so that the data assigned to the identifier is usable.
In order to reference a property that does not follow the rules for a properly formatted identifier, you must use bracket notation instead of dot notation for the property accessor:
var object = JSON.parse('{"#text":"https://lastfm-im...png","size":"extralarge"}')
console.log(object['#text'])
you cam modifide the response - loop throw it wite map- and chenge the object key -see here:
JavaScript: Object Rename Key
You can use square bracket notation instead of dot notation. like (Object mutation is highly not recommended)
//to access it u can use square bracket notation like k["objectname"]
let k = {"#test":"some data"}
alert("data is "+k["#test"])

Use key's value as key in key-value pair in Javascript

How can you use the value of a key-value pair as the key in a different key-value pair in javascript?
I'd like to do the following:
var gizmos = {gizmo1: "G1"};
var things = {gizmos.gizmo1: "T1"};
So that things essentially equals:
var things = {"G1": "T1"};
Like this:
var gizmos = {gizmo1: "G1"};
var things = {};
things[gizmos.gizmo1] = "T1";
There's no way to do it as part of the object initializer (aka object "literal"), you have to do it after.
The reason it works is that in JavaScript, you can access (get or set) a property on an object in two ways: Either using dotted notation and a literal, e.g. foo.bar, or using bracketed notation and a string, e.g. foo["bar"]. In the latter case, the string doesn't have to be a string literal, it can be the result of any expression (including, in this case, a property lookup on another object).
Side Note: If you change gizmos.gizmo1 after you do the things[gizmos.gizmo1] = "T1"; line, it does not change the name of the property on things. There's no enduring link, because the value of gizmos.gizmo1 was used to determine the property name during the things[gizmos.gizmo1] = "T1"; line (just like it is in any other expression).
var gizmos = {gizmo1: "G1"};
var things = {};
things[gizmos.gizmo1]="T1";
To get the value for a given key on an object use object["key"] or object.key

Serialize a javascript array

I have observed that in php you can encode an array and the resulting json does not carry the square brackets.However,in my javascript array,
var arrCars = new Array("Toyota", "Mercedes", "BMW");
var jsonStr = JSON.stringify(arrCars);
alert(jsonStr);
i keep getting the square brackets.I have also noticed that if i use json stringfy,
var foo = {};
foo.bar = "new property";
foo.baz = 3;
var JSONfoo = JSON.stringify(foo);
i get the json without the square just like i wanted.What must i do to my array to do away with the brackets?.
There's a difference between an array ([]) and an object ({}) in javascript. Your first example uses an array. Your second example uses an object. The main difference is that when you have an array ([]) the index can only be a zero based integer. Whereas an object can have property names that are strings.
The correct JSON for the array in your first example is ["Toyota","Mercedes","BMW"], and the correct JSON for the object in your second example is either {"bar":"new property","baz":3} or {"baz":3,"bar":"new property"}.
A JSON string contains either an object or an array, so it always has either curly brackets {} or square brackets [].
If you get anything else, the result is not correct. If you expect anything else, your expectation is wrong.
If you want the curly brackets instead of the square brackets, you have to serialise an object, not an array.
Not sure why you don't want brackets, since brackets are the normal way to make an array literal (as opposed to using the Array() function, as you do, which is way old-school)
If you want the JSON without the brackets, such as if you are building a bigger JSON string or something, you can use something like this:
function jsonifyArrayWithoutBrackets(a) {
var output = [];
for (var i=0; i<a.length; i++)
output.push(JSON.stringify(a[i]));
return output.join(',');
}
Or, obviously, just trim the brackets off after using a single call to JSON.stringify().

Javascript use reserved keyword as key

Doing so
var x = new Array();
x['length']=5;
will make x an array of 5 undefined items, but I actually want to have the value '5' stored at key 'length'.
Is that possible?
In javascript arrays do not have keys. You are looking for objects:
var x = {}
x.length = 5;
I have to parse a file containing many words and store the number of occurences of each word
Use an object, and make the words the keys. You aren't storing sequential / ordered data, so you shouldn't use an array.
var word_count = {};
for (var i; i < words.length; i++) {
var word = words[i];
if (word_count[word]) {
word_count[word]++;
} else {
word_count[word] = 1;
}
If you want to do this you'd be better off creating an object rather than an array. This should give you what you want.
var x = {};
x['length'] = 5;
You can call methods on a javascript object using two different syntaxes. The familiar 'dot' syntax with parens to invoke the method, and the square bracket syntax. You can 'call' a method on a javascript object using the syntax myObj["methodname"](args). This is handy when you want to construct the method name dynamically using strings. Remember, objects in javascript are very much like a hash table (dictionary) where keys denote property and function names. If a key's value holds a function, it can be invoked (using parentheses).
In your example, Array has a method called 'length'. You are inadvertently calling its setter (which sets the length of the array to empty values, i.e., undefined).
Putting that all aside, you really do want a hash (associative array) in this case. An array is an offset indexed data structure.
A simple object literal like myObj = {} will suffice to give you hash semantics (again, objects in javascript are already like hashes) and you can then call myObj.whatever = "some value"
You could use objects instead of arrays to store your data. But if you need to use Arrays (you might need to use their functionality), You could cripple the words and store them as array keys.
Use some kind of simple rule to follow to bypass all the possible keywords. For example prefix all your array keys with a "_" character. This way you could always restore the original words from the keys, by simply removing their first character, and you are sure you are not referencing any specific property of the Array objects (like the length property).

For .. in loop?

I'm losing it here.. I am now extremely confused about how this loop works.
From w3 schools:
var person={fname:"John",lname:"Doe",age:25};
for (x in person)
{
document.write(person[x] + " ");
}
person is an object with properties right? How are those properties being accessed with the brackets? I thought that was for arrays?
Why does this also work, and shouldn't it ONLY be like this?:
var person=[];
person["fname"] = "John";
person["lname"] = "Doe";
person["age"] = "25";
for (x in person)
{
document.write(person[x] + " ");
}
There are two ways in which you have access to an object's properties:
obj.key
obj['key']
The advantage of the second method is that you can also provide the key dynamically, e.g. obj[x] in your example. obj.x would literally mean the x property (i.e. obj['x']), which is not what you want.
Arrays only work with brackets, but brackets are not limited to arrays. Arrays are under the hood also objects, but designed for numeric keys. You can still add properties with non-numeric keys to them, but that's not what they are designed for.
You can access both Object literals as well as Arrays with the bracket operator in JavaScript. For Objects the bracket operator accesses a member of the Object by converting the value in the bracket to a String (if it is not a String) and checking if it is indeed a property (mdc).
Your second example suggests using an "associative Array" which is discouraged in JavaScript (link).
To answer your question: the standard way (imo) of writing a Map like structure -- i.e. an Object holding key-value-pairs -- to iterate over using a for-in loop is the Object literal; the standard way of writing a more traditional array is the Array Object.
var map = { "a": "string" , "b": 0 , "c": null } ;
for(key in map) console.log("(!!) map # " + key + " : " + map[key] ) ;
var list = ["string",0,null] ;
for(i = 0 ; i < list.length ; i++) console.log("(!!) list # " + i " : " + list[i] ) ;
JavaScript objects properties can be accessed both with object[key] and object.key (and some other ways, most probably). Just the way they work.
Your second example, an array is a special object but still an object.
http://bonsaiden.github.com/JavaScript-Garden/#object.general
"The properties of an object can be accessed in two ways, via either the dot notation, or the square bracket notation."
in js objects are asociative arrays, meaning that they are nothing but a collection of key-value pairs.
If you are confused about the brakets, don't be! Javascript object properties can be accesed via the "." or the "[]" construction:
var a = {key : 'val'};
alert(a['key'] === a.key);
In most cases they work the same.
It's just a matter of preferences and browser implementation (eg : firefox works faster with brackets, while chrome works faster with the dots).
There are situations, where the dot construcion will fail: supose you have an object which has a property named "some-key".
If you want to acces it with the dot notation : object.some-key, you will most certain get an error, because the code is being interpreted as aa difference between 2 values : object.some - key. In this case you should use the brackets : object['some-key'].
There are other cases too, where the key contains a special character such as .,,,;,\,*...etc that already has a interpretation in javascript.

Categories