5

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);
3
  • 1
    Why you want to do it. You can always use obj.a, obj.b, obj.c Commented Jan 24, 2014 at 5:22
  • 1
    Please note that your question/problem has nothing to do with JSON. After the JSON is parsed, you are working with regular JS arrays and objects. Commented Jan 24, 2014 at 5:39
  • @Felix Kling Thank you, noted. Commented Jan 24, 2014 at 6:11

3 Answers 3

8

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);
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for your speedy response. Your example works but for some reason misses out the last entry in the array so I get uncaught reference error: c is not defined
Ignore that, it was just clashing with other variables of the same name. Rookie error.
Great answer! But what if you wanted to only load the variables into a local function scope, not global window scope. (I know this is an edge case need, but would be cleaner.) Maybe that would require eval()?
@SimonEast: I can't think of any way to do it other than eval(), but I would be very careful when considering that approach. If your values originate from user input, then malicious users could potentially inject code that will be executed.
-1

In Javascript, arrays are objects, and objects are arrays. But they have been initialized with special behavior.

Take a look at this answer:

https://stackoverflow.com/a/4215753/1311986

You will find that you want to do something very similar.

5 Comments

Not really true. Objects are not arrays. Sure, they can be used similarly, in that if you have an object like var obj = {a: 1};, you can get the value by doing something like obj['a'], but that doesn't mean it's an array. Here's an example. And, in any case, the answer is not really relevant to the question. He's (basically) asking how to take the properties of an object and turn them into separate variables, similar to PHP's extract() function.
I think more confusion arises since JS will allow you to do something like var arr = []; arr['key'] = 'value';, which leads you to believe that it's an array with string keys, but what's really happening is that you're setting a property on the array object. Proof of this is that after you've done this, you can still access the 'value' property using arr.key.
Objects are not arrays ({} instanceof Array is false). If you think that because you can access objects via bracket notation (obj[foo]), well, that's because it's one of the fundamental ways of accessing an object property. The bracket notation has nothing whatsoever to do with arrays. If it was allowed to access property names starting with digits to be used in dot notation, i.e. like arr.1, then you could access arrays also like this. But since it is not allowed, bracket notation is the only of these two ways to access the elements of an array.
@Travesty3: It's not silently converted to an object. Arrays are objects from the very beginning (with additional methods and behaviors).
@FelixKling: Yeah, you're right. Bad wording on my part. Good thing I was still within my edit period ;-)
-1

First of all {"a":"apple,"b":"banana","c":"carrot"} is not an array, it's a simple JSON String.

Now to parse JSON String you can use

JSON.parse()

It is supported by all Modern Browsers and you can also find the library here

You may try to do this with your app: assuming your jsonString as an array.

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

You will get the output something like this:

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

Hope this solves your problem.

3 Comments

In your example, jsonString is not a string though. It's an array. Also, what's with the ###?
Your claim that {"a":"apple,"b":"banana","c":"carrot"} is a simple JSON String, may be incorrect. We can't really be sure without the context around it, but if my code was: var obj = {"a":"apple,"b":"banana","c":"carrot"};, then obj is a JavaScript object, not requiring any JSON parsing. Also, his example is not surrounded in square brackets, so parsing it (assuming it's a string) will return a single object, not an array of objects.
Sorry i just kept the jsonString from reference, he might be getting a json array string, assuming that i responded to the question.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.