Convert JSON array to separate JS variables

I have a JSON array:

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

I want to split each part of the array into separate variables, i.e.

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

My glasses are disabled, but I can’t find the right way to do this. I am new to JSON and read fairly fairly, but what I need seems not to be mentioned in my hands.

EDIT: There seems to be confusion as to whether my array is stringor object. I get 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

json.stringify(data);
+4
source share
3 answers

, , .

, . , :

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);
+7

Javascript - , - . .

:

fooobar.com/questions/28644/...

, - .

0

{ "a": "apple," b ":" banana "," c ":" carrot "} , JSON.

JSON

JSON.parse()

,

:     jsonString .

 var jsonObj = $.parseJSON("### json string #####");

 for(var index = 0; index < jsonObj.length; index++){
     console.log("a:"+jsonObj[index].a+",b:"+jsonObj[index].b+",c:"+jsonObj[index].c);
 }

:

a: apple, b:banana, c:carrot
. . . 
. . .

, .

0

Source: https://habr.com/ru/post/1523465/


All Articles