Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert JSON array into individual JS variables

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);
like image 643
Wildcard27 Avatar asked Jan 24 '14 05:01

Wildcard27


1 Answers

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);
like image 199
Travesty3 Avatar answered Oct 30 '22 14:10

Travesty3