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?

2
  • 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! Commented Aug 4, 2010 at 23:45
  • changing the parser to reader Commented Aug 4, 2010 at 23:53

2 Answers 2

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.

Sign up to request clarification or add additional context in comments.

2 Comments

I'm pretty sure this question is a duplicate, because I think I posted this exact answer before.
sorry , not sure. I used js array "push" to convert object into array.
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.