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

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
  • It should work fine. `document.write()` is not the best way to inspect variables. Use `console.log()` instead. – VisioN Feb 17 '13 at 11:59
  • That's not a JSON string, but a simple object/array literal! – Bergi Feb 17 '13 at 11:59
  • Can you make a demo that shows what `document.write(arr)` actually prints? – Bergi Feb 17 '13 at 12:00
  • it prints the same array [{"Category": {"cell":{"question1":{"que1":"What is the cell?"},........... –  Feb 17 '13 at 12:03
  • 1
    i need to say, que the array was extracted of json file, and I did a var arr = JSON.stringify(arrjson) –  Feb 17 '13 at 12:04
  • 2
    Then use `arrjson[0].Category` instead. `arr` is a string. – Felix Kling Feb 17 '13 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. – Popnoodles Feb 17 '13 at 12:09
  • @popnoodles yeah you right, now it works, I deleted var arr = JSON.stringify(arrjson), and I just put document.write(arrjson[0].Category) –  Feb 17 '13 at 12:11

1 Answers1

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.

Popnoodles
  • 28,090
  • 2
  • 45
  • 53