doon
doon

Reputation: 2361

How to read arrays in Json using JavaScript

I have a Json data as listed below:

var x = {

"array1":"['x1','x2']",
"array2":"['a1', 'a2']"
}

I need to print the individual elements of the array as below

x1
x2
a1
a2

When I do var y = JSON.parse(x), it gives me "Unexpected token o"

It seems to be coming from the JSON.parse line. If I do x = '["x1", "x2"]', there is no error but I need to have two arrays in the JSON. So how do I read them

Thanks for any answers

Upvotes: 1

Views: 594

Answers (5)

alexandru.pausan
alexandru.pausan

Reputation: 479

What you have there, that 'x' variable var x = {"array1":[...]...} is already a javascript object, so you can simply pass through the object keys and display the values.

Given 'x' as the object you can have something like:

var key,       
    result = '';

for (key in x) { 
    if (x.hasOwnProperty(key)) {
        result = result + x[key].join('\n') + '\n';
    }
}
// There you have the result...

As John said earlier, for JSON.parse() you wold need a string as a parameter to be able to parse it into a javascript object.

Upvotes: 0

Jason Cust
Jason Cust

Reputation: 10899

That is not JSON. JSON is a string and not an object hence its abbreviation of JavaScript Object Notation. What you have is colloquially referred to as a POJO or Plain Old JavaScript Object. They are different. The former is a data exchange format similar to YAML or XML while the latter is an actual object with properties and values.

Your POJO does have JSON values but since it is already an object you can't use JSON.parse to parse the entire object. That is where the "o" is coming from in the error message. JSON.parse will coerce the first argument to a string if it is not a string:

var foo = {};
JSON.parse(foo); // is essentially doing this foo.toString() which is "[object Object]"
JSON.parse('{}'); // This would parse to an empty object though since it is a string

So now when it attempts to parse "[object Object]" it sees what may be an array but then encounters a character that hasn't been quoted, the "o" in "object", and therefore throws an error.

For your example to be JSON you would need to write it as:

var json = '{"array1":["x1","x2"],"array2":["a1","a2"]}';
var x = JSON.parse(json);

document.write('<pre>' + JSON.stringify(x, null, 4) + '</pre>');

And so, now that we have a real JSON value we can answer your original question:

var json = '{"array1":["x1","x2"],"array2":["a1","a2"]}';
var x = JSON.parse(json);

var vals = Object.keys(x).sort().reduce(function (arr, key) {
  arr = arr.concat(x[key]);
  return arr;
}, []).join('\n');

document.write('<pre>' + vals + '</pre>');

Upvotes: 4

WeisserHund
WeisserHund

Reputation: 160

Create your array in many different ways - two examples

var x = [{array1:['x1','x2']},{array2:['a1','a2']}]
x[1].array2 produces ["a1", "a2"]
x[1].array2[0] produces "a1"

var xx = {array1:['x1','x2'],array2:['a1','a2']}
xx.array2 produces ["a1", "a2"]
xx.array2[0] produces "a1"

third example

var xxx = {array1:{x1:'x1',x2:'x2'},array2:{a1:'a1',a2:'a2'}}
xxx.array1.x1 produces "x1"

Upvotes: 0

messerbill
messerbill

Reputation: 5629

so, you can use this script to do that (correct json too - http://jsonformatter.curiousconcept.com/ -, don't know why this downrate.....i guess a noob didnt realize :D):

var x = {
 "array1": ["x1", "x2"],
 "array2": ["a1", "a2"]
}

for (var key in x) {
 if (x.hasOwnProperty(key)) {
 document.getElementById("test").innerHTML += key + " -> " + x[key]+" <br>";
}
}

i've created a working fiddle here:

https://jsfiddle.net/rjzzqLmr/1/

Upvotes: -1

Fedor
Fedor

Reputation: 1444

I think your JSON should be like the following

{
  "array1": ["x1", "x2"],
  "array2": ["a1", "a2"]
}

Upvotes: 0

Related Questions