Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
26
rated 0 times [  27] [ 1]  / answers: 1 / hits: 5681  / 11 Years ago, fri, january 24, 2014, 12:00:00

I have a JSON array:



{a:apple,b:banana,c:carrot}


I want to split each part of the array into seperate variables, ie,



a = apple,
b = banana;
c = carrot;


I have googled my goggles off but can't seem to find a correct way to do this. I am new to JSON and have done a fair bit of reading but what I am after doesn't seem to be referenced within my grasp.



EDIT: There seems to be confusion as to whether my array is a string or object. I am receiving a response from PHP as follows:



$json = array(
'a' => $a,
'b' => $b,
'c' => $c,
);
echo json_encode($json);


My JS code is as follows:



var data = ajax.responseText;
data = JSON.parse(data);


I get {a:apple,b:banana,c:carrot} as a result of



json.stringify(data);

More From » arrays

 Answers
3

One example of how you can do this is found here.



It assumes you want to put the variables into global scope. If this is the case, this will work:



function extract(variable) {
for (var key in variable) {
window[key] = variable[key];
}
}

var obj = {a:apple,b:banana,c:carrot}

extract(obj);

alert(a);
alert(b);
alert(c);

[#48392] Thursday, January 23, 2014, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
deanna

Total Points: 84
Total Questions: 86
Total Answers: 107

Location: Cyprus
Member since Wed, Dec 8, 2021
3 Years ago
;