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);
Wildcard27
  • 1,437
  • 18
  • 48

3 Answers3

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);
Travesty3
  • 14,351
  • 6
  • 61
  • 98
  • 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` – Wildcard27 Jan 24 '14 at 06:14
  • Ignore that, it was just clashing with other variables of the same name. Rookie error. – Wildcard27 Jan 24 '14 at 06:40
  • 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()`? – Simon East Jun 15 '18 at 05:49
  • 1
    @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. – Travesty3 Jun 18 '18 at 12:00
-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.

Community
  • 1
  • 1
Nexim
  • 54
  • 5
  • 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](http://jsfiddle.net/uq39L/). 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()`](http://us1.php.net/extract) function. – Travesty3 Jan 24 '14 at 05:36
  • 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`. – Travesty3 Jan 24 '14 at 05:41
  • 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. – Felix Kling Jan 24 '14 at 05:41
  • @Travesty3: It's not silently converted to an object. Arrays **are** objects from the very beginning (with additional methods and behaviors). – Felix Kling Jan 24 '14 at 05:42
  • @FelixKling: Yeah, you're right. Bad wording on my part. Good thing I was still within my edit period ;-) – Travesty3 Jan 24 '14 at 05:44
-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.

NarendraSoni
  • 2,210
  • 18
  • 26
  • In your example, `jsonString` is not a string though. It's an array. Also, what's with the `###`? – Felix Kling Jan 24 '14 at 05:45
  • 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. – Travesty3 Jan 24 '14 at 05:48
  • Sorry i just kept the `jsonString` from reference, he might be getting a `json array string`, assuming that i responded to the question. – NarendraSoni Jan 24 '14 at 05:50