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);
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With