1

I have the next array json, How could I read it? I already tried with document.write(arr), and it works, but If I put document.write(arr[0].Category) it shows undefined,

var arr = [{"Category":
{"cell":{"question1":{"que1":"What is the cell?"},
"option1":{"op1":"The cell is the basic structural and functional unit",
"op2":"is a fictional supervillain in Dragon Ball"},"answer1":"opt1"}}},
{"Category":{"Mars":{"question1":{"que1":"How many moons does Mars?"},
"option1":{"op1":"5","op2":"2"},"answer1":"opt2"}}}]

By the way the array is well formet, because if I do document.write(arr) it return the same array

8
  • It should work fine. document.write() is not the best way to inspect variables. Use console.log() instead. Commented Feb 17, 2013 at 11:59
  • That's not a JSON string, but a simple object/array literal! Commented Feb 17, 2013 at 11:59
  • 1
    i need to say, que the array was extracted of json file, and I did a var arr = JSON.stringify(arrjson) Commented Feb 17, 2013 at 12:04
  • 2
    Then use arrjson[0].Category instead. arr is a string. Commented Feb 17, 2013 at 12:08
  • 4
    arr is not a string in the code given, @chikatetsu where did you do var arr = JSON.stringify(arrjson)? This conflicts with the code you have given. Commented Feb 17, 2013 at 12:09

1 Answer 1

2

The code does work. Look: http://jsfiddle.net/5GTWp/

console.log(arr[0].Category);
document.write(arr[0].Category.cell.question1.que1);

Logs the object,
writes: What is the cell?

document.write(arr[0].Category) 

writes [object Object], not undefined.

Problem is not in the code given.

EDIT: Further information. OP has added in a comment "i need to say, que the array was extracted of json file, and I did a var arr = JSON.stringify(arrjson)"

If you make arr a string it's not going to work. The example you gave != your problem.

document.write(arrjson[0].Category);

is the object you are looking for.