how to parse an associative array through json in javascript - javascript

I have a 2-D php array which i am encoding through JSON. My 2d array in php is something like this:
$array['A'][12] = 8;
$array['A'][8] = 21;
$array['B'][17] = 19;
$array['B'][9] = 12;
when I do echo json_encode($array); and alert this as Ajax xmlhttp.responsetext i get this in my alert box : {"A":{"12":"8","8":"21"},"B":{"17":"19","9":"12"}}
which is absolutely fine. Now i need to parse it in javascript so i used the JSON.parse() function. The problem is when i access the A and B fields of the string. I get this in my alert boxes: Object object. How to parse this associative array? I am a beginner in AJAX and JSON so please help.

var array = JSON.parse(yourResponseData);
array.A // Object
array.A['12'] //8
You can't access the key '12' via the dot syntax becase no variable name can start with a number.

You can use console.log() rather than alert() to see the complete structure of that parsed json object.
You can easily retrieve the value by using . notation or [] brackets:
For example:
var returned = JSON.parse(tran.responseText);
console.log(returned['A']['8']); //which should give you '21' based on your case

Related

Nan is being set in json model when trying to bind with odata response

I am creating a restructured json model in our sapui5 app wherein the data is being received from the odata response. I am using the json.setproperty() method.
if i try n access the value with following methods
var two = 2;
var test = "Count"
var three = test+two
alert(odata.results[0][three]);
correct value is being alerted with object notation as against Nan being alerted if dot notation was used.
so in a loop im trying to fill the content of the json
for(var i=0;i<=count-2;i++){
var z = "Count"+i;
countjson.setProperty("/data/data/"+i+"/Count",odata.results[0].z);
countjson.setProperty("/data/data/"+i+"/Count",odata.results[0][z]);
}
Nan is being returned when im trying with the dot notation and undefined is being returned with object notation.
if i hardcode the path i.e odata.results[0].Count4 i am getting the 4th element from the odata resp and getting set in all fields of the new json.
Please help me with the above.
Best regards
archit
You cannot access a multidimensional array like that. Instead try using this -
odata.results[0][odata.results[0].indexOf(three)]

How does JSON.parse() work?

I have not worked too much on javascript. And, I need to parse a JSON string. So, I want to know what exactly JSON.parse does. For example :
If I assign a json string to a variable like this,
var ab = {"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}};
Now when I print 'ab', I get an object.
Similarly when I do this :
var pq = '{"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}}';
var rs = JSON.parse(pq);
The 'rs' is the same object as 'ab'. So what is the difference in two approaches and what does JSON.parse did differently ?
This might be a silly question. But it would be helpful if anybody can explain this.
Thanks.
A Javascript object is a data type in Javascript - it's have property and value pair as you define in your first example.
var ab = {"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}};
Now What is Json : A JSON string is a data interchange format - it is nothing more than a bunch of characters formatted a particular way (in order for different programs to communicate with each other)
var pq = '{"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}}';
so it's is a String With json Format.
and at last JSON.parse() Returns the Object corresponding to the given JSON text.
Here is my explanation with a jsfiddle.
//this is already a valid javascript object
//no need for you to use JSON.parse()
var obj1 = {"name":"abcd", "details":"1234"};
console.log(obj1);
//assume you want to pass a json* in your code with an ajax request
//you will receive a string formatted like a javascript object
var str1 = '{"name":"abcd", "details":"1234"}';
console.log(str1);
//in your code you probably want to treat it as an object
//so in order to do so you will use JSON.parse(), which will
//parse the string into a javascript object
var obj2 = JSON.parse(str1);
console.log(obj2);
JSON, or JavaScript Object Notation, is a minimal, readable format for structuring data. It is used primarily to transmit data between a server and web application, as an alternative to XML.
Your 'ab' variable isn't a string, it is a proper javascript object, since you used the {} around it. If you encased the whole thing in "" then it would be a string and would print out as a single line.
Data Type!! That is the answer.
In this case, ab is an object while pq is a string (vaguely speaking). Print is just an operation that displays 'anything' as a string. However, you have to look at the two differently.
String itself is an object which has properties and methods associated with it. In this case, pq is like an object which has a value: {"name":"abcd", "details":{"address":"pqrst", "Phone":1234567890}} and for example, it has a property called length whose value is 66.
But ab is an object and you can look at name and details as its properties.
What JSON.parse() did differently was that, it parsed (converted) that string into an object. Not all strings can be parsed into objects. Try passing {"name":"abc" and JSON.parse will throw an exception.
Before parsing, pq did not have any property name. If you did something like pq.name, it'll return you undefined. But when you parsed it using JSON.parse() then rs.name will return the string "abcd". But rs will not have the property length anymore because it is not a string. If you tried rs.length then you'll get a value undefined.

How can I properly use the javascript function JSON.parse()?

I have an array that is printed in JSON
[{"Name":"John Ranniel","Age":"19","City":"Manila"},{"Contact":"09197875656","Relation":"Sister"}]
For some reason, I divided the JSON into two parts.
In javascript I used JSON.parse() to decode the JSON above.
for example:
var arr = JSON.parse(response); //The response variable contains the above JSON
alert(arr[0].Name) //Still it outputs John Ranniel, but If i change the content of the alert box on the second part of the JSON,
alert(arr[1].Contact) // It has no output, I don't know if there is a problem with the index of the array.
Make sure your JSON is a string type:
'[{"Name":"John Ranniel","Age":"19","City":"Manila"},{"Emergency Contact":"09197875656","Relation":"Sister"}]'
and then, you can use,
var arr = JSON.parse(response); //The response variable contains the above JSON
console.log(arr[0].Name);
console.log(arr[1]['Emergency Contact']); // There is no 'Contact' property iun your object, and you should use this when there's a space in the name of the property.
See:
var response = '[{"Name":"John Ranniel","Age":"19","City":"Manila"},{"Emergency Contact":"09197875656","Relation":"Sister"}]';
var arr = JSON.parse(response);
console.log(arr[0].Name);
console.log(arr[1]['Emergency Contact']); // There is no 'Contact' property iun your object, and you should use this when there's a space in the name of the property.
You are trying to parse something which is already a JavaScript object, and does not need to be parsed. You need to parse JSON strings. This is not a JSON string. It's a JavaScript object.
Consider the following:
JSON.parse([1,2])
This will coerce the array [1,2] into the string "1,2". JSON.parse will then choke on the ,, since it doesn't belong there in a valid JSON string.
In your case the object will be coerced to the string
"[object Object],[object Object]"
JSON.parse will accept the leading [ as the beginning of the array, then throw on the following character, the o, since it does not belong there in a proper JSON string.
But you say that the JSON.parse worked and resulted in arr. In other words, the parameter you fed to JSON.parse apparently was a string, and was parsed correctly. In that case, the alerts will work fine.
Your JSON structure is array, must be parse to JSON,use JSON.stringify parse this to JSON:
var json = [{"Name":"John Ranniel","Age":"19","City":"Manila"},{"Contact":"09197875656","Relation":"Sister"}];
var str = JSON.stringify(json);
console.log(json);
var arr = JSON.parse(str);
alert(arr[0].Name) //Still it outputs John Ranniel, but If i change the content of the alert box on the second part of the JSON,
alert(arr[1].Contact) // It has no output, I don't know if there is a problem with the index of the array.
Demo: Link
This JSON is array, you can use directly:
var json = [{"Name":"John Ranniel","Age":"19","City":"Manila"},{"Contact":"09197875656","Relation":"Sister"}];
alert(json[0].Name);
alert(json[1].Contact);

JSON.parse giving me object instead of result

I have variable in javascript which is coming from php by json_encode.
While I am psrsing it with JSON.parse(variable). It alert me objects instead of actual result.
CODE:
var a = '<?php echo json_encode($over_branch_array); ?>';
a = JSON.parse(a);
alert(a);
EDIT:
basically I need to map my php array.
a = a.map(function(v){
return { id : v.branch, text : v.branch };
});
If I will do JSON.stringify then I won't be able to do that..
alert performs a toString conversion on objects before displaying them. You'll get a result like this.
If you want to view the contents of the object, either console.log it or JSON.stringify it.
EDIT:
When I say use JSON.stringify I mean do it to show what is actually in the object:
alert(JSON.stringify(a));

Javascript Double indexing Associative "array" Object [duplicate]

I am looking for a solution to create a single multidimensional associate array in javascript.
What I have: I have a mysql database I am accessing with php and have an array containing all fields (key,value pairs) in a single record. Their are upwards of 30 fields in each record so I am looking for a dynamic solution.
In the html coding, there is a form that is used to update a specific record in the table. I am using a function call on each input to fill a javascript array by key and value. The keys are identical to the keys in the php array.
In the function I am doing a json_encode call on the php array to pull in the "old" data to make it accessible to javascript.
What works: I am able to create a dynamic javascript associate array from the new data coming from the input function calls. I have tested this out using an alert after each call to the function.
What I need: A method to change the javascript array to a multidimensional array, pulling in the old value and adding it to the new array tied to the original key.
This works:
var changes={};
function change(key,value) {
changes[key[value]]=value;
for (key in changes) {
alert('key: '+key+'... value: '+changes[key]);
}
}
this is along the lines of what I am looking for:
var changes={};
function change(key,value) {
var oldInfo = eval(<? echo json_encode($oldInfo); ?>); //this from the php array
changes[key[newValue]]=value;
changes[key[oldValue]]=oldInfo[key];
for (key in changes) {
alert('key: '+key+'... value: '+changes[key[newValue]]);
}
}
Can someone point me in the right direction?
To clarify:
My php array $oldInfo holds the old information from the table, for example:
{fName=>"charles",lName=>"madison", etc.}
The javascript array hold new information:
{fName=>"Charlie",lName=>"Madison", etc.}
I would like a new multidimentional array (PHP) (or object in JavaScript) that would look something like this:
{fName=>{"charles","Charlie"}, lName=>{"madison","Madison"}, etc.}
lName and fName would be the key fields that are synonymous to both the PHP array and the JavaScript object.
It's really unclear what you want, but there are a couple of serious flaws with your logic:
var changes={}; ///this one way of declaring array in javascript
No, it isn't. That's an Object, which is very different from an array.
eval(<? echo json_encode($oldInfo); ?>);
You don't need eval here. The output of json_encode is JSON, which is a subset of JavaScript that can simply be executed.
changes[key[value]]=value;
This is totally wrong, and still a single-dimensional array. Assuming key is an array, all you're doing is inverting the keys/values into a new array. If key looks like this before...
'a' => 1
'b' => 2
'c' => 3
... then changes will look like this after:
1 => 'a'
2 => 'b'
3 => 'c'
For a multidimensional array, you need two keys. You'd write something like changes[key1][key2] = value.
Your variable naming is wrong. You should never see a line that reads like this: key[value]. That's backwards. The key goes between the [], the value goes on the other side of the =. It should read something like array[key] = value.
RE: Your clarification:
This doesn't work: {fName=>{"charles","Charlie"},...}. You're confusing arrays and objects; Arrays use square brackets and implicit numeric keys (["charles", "Charlie"] for example) while Objects can be treated like associative arrays with {key1: "value1", key2: "value2"} syntax.
You want an array, where each key is the name of a property and each value is an array containing the old and new values.
I think what you want is actually quite simple, assuming the "value" you're passing into the function is the new value.
var changes = {};
var oldInfo = <?= json_encode($oldInfo) ?>;
function change(key, value) {
changes[key] = [ oldInfo[key], value ]
}
This :
changes[key[newValue]]
Should be:
changes[key][newValue]
What I need: A method to change the javascript array to a multidimensional array, pulling in the old value and adding it to the new array tied to the original key.
Use aliases for the numeric indices to do this:
var foo = ["Joe","Blow"];
var bar = ["joe","blow"];
var names = {};
foo.fname = foo[0];
bar.fname = bar[0];
foo.lname = foo[1];
bar.lname = bar[1];
names.fname = [foo.fname,bar.fname];
names.lname = [foo.lname,bar.lname];

Categories

Resources