views:

41

answers:

2

Hi, I wrote the json reader to read the data & works fine with the below data.

{"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": [
      {"value": "New", "onclick": "CreateNewDoc()"},
      {"value": "Open", "onclick": "OpenDoc()"},
      {"value": "Close", "onclick": "CloseDoc()"}
    ]
  }
}}

but the when json returns the single menuitem from api like

{"menu": {
  "id": "file",
  "value": "File",
  "popup": {
    "menuitem": 
      {"value": "Close", "onclick": "CloseDoc()"}

  }
}}

menuitem is an object instead of an array. So, my json reader is failing to read as i'm readin the array of menuitem by looping.

solution is greatly appreciated. How this is handled by other major sites?

A: 

http://api.jquery.com/jQuery.parseJSON/

hvgotcodes
but its used to parse the json to avoid any syntax or any other issues.?Am i not right
jaan
i dont really understand the question -- why are you writing your own json parser?
hvgotcodes
oops its the reader.
jaan
A: 

jQuery's makeArray is perfect for this.
http://api.jquery.com/jQuery.makeArray/

It'll take anything and return a array, so if it's already an array it passes it as-is, but if it's a scalar it makes a single-valued array out of it. Then you can iterate the result.

darkporter
I'm pretty sure this question is a duplicate, because I think I posted this exact answer before.
darkporter
sorry , not sure.I used js array "push" to convert object into array.
jaan