2

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?

Nick Craver
  • 623,446
  • 136
  • 1,297
  • 1,155
jaan
  • 143
  • 1
  • 1
  • 9
  • before reading the json can i check for an menuitem array ,if not can i convert that to array?Please suggest me the methods to convert in fast way Thanks in advance! – jaan Aug 04 '10 at 23:45
  • changing the parser to reader – jaan Aug 04 '10 at 23:53

2 Answers2

1

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.

jpsimons
  • 27,382
  • 3
  • 35
  • 45
0

Assuming you want to read the 'value' of menuitem,you can use

if(menuitem.value!=undefined)//this will return undefined if the menu item is an array

Then the other thing is to use menuitem[0].value if the above condition is false. Hope this solves your issue to some extent.

kavinhuh
  • 739
  • 1
  • 9
  • 30