Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

JSON to associative array in jquery

I read more here, but I have not found the answer to my problem My problem:

I have (from php via ajax return json string)

str = '[{"id":"159","pavadinimas":"Building B","_id":"200",.................}]';

this is JSON string and I do obj = $.parseJSON(str); i can take any value in that way like alert(obj[0]._id) I get 200.

But how I can get associative array from json like:

dataArray = [
"id":"159",
"pavadinimas":"Building B",
"_id":"200",
...
]

I want get value 200 like that

val = dataArray['_id'];
like image 875
Vacys Avatar asked Jul 04 '26 08:07

Vacys


2 Answers

There is no associative array concept in javascript, but only object.

var arr = $.parseJSON(str);
var obj = arr[0];
var _id = obj['_id']
like image 91
xdazz Avatar answered Jul 06 '26 23:07

xdazz


Javascript does not have associative arrays. You will have to use objects, which use curly brackets {} instead.

dataObj = {
    "id":"159",
    "pavadinimas":"Building B",
    "_id":"200",
    ...
}

console.log( dataobj.id );
console.log( dataobj['id'] );

Both works the same.

So for your example, you can access the object the way you would expect an associative array to work.

like image 26
MildlySerious Avatar answered Jul 06 '26 22:07

MildlySerious