Tutorial :javascript and json



Question:

I'm using javascript with a json library and running into a little trouble. Here's my json output:

{      "artist": {          "username": "myname",          "password": "password",          "portfolioName": "My Portfolio",          "birthday": "2010-07-12 17:24:36.104 EDT",          "firstName": "John",          "lastName": "Smith",          "receiveJunkMail": true,          "portfolios": [{              "entry": [{                  "string": "Photos",                  "utils.Portfolio": {                      "name": "Photos",                      "pics": [""]                  }              },              {                  "string": "Paintings",                  "utils.Portfolio": {                      "name": "Paintings",                      "pics": [""]                  }              }]          }]      }  }  

In javascript I'm trying to access the entries in the map like so:

var portfolios = jsonObject.artist.portfolios.entry;  var portfolioCount = portfolios.length;    for ( var index = 0;  index < portfolioCount; index++ )   {     var portfolio = portfolios[index];     txt=document.createTextNode("Portfolio Name: " + portfolio['string']  );     div = document.createElement("p");     div.appendChild ( txt );     console.appendChild(div);  }  

but portfolios is "undefined". What's the correct way to do this?


Solution:1

Look at your JSON results. portfolios is a one-element array; portfolios[0] is an object containing a single key, entry, which maps to an array of two objects that have both string and utils.Portfolio keys. Thus, the syntax jsonObject.artist.portfolios.entry will not work. Instead, you want jsonObject.artist.portfolios[0].entry.

If possible, I would suggest changing whatever code generates those JSON results to remove the entry level of indirection entirely, e.g. like so:

{    "artist": {      /* ... */      "portfolios": [        {          "string": "Photos",          "utils.Portfolio": {              "name": "Photos",              "pics": [""]          }        },        {            "string": "Paintings",            "utils.Portfolio": {                "name": "Paintings",                "pics": [""]            }        }      ]    }  }  

Then you could access it with

var portfolios = jsonObject.artist.portfolios;  for (var i = 0, portfolio; portfolio = portfolios[i]; ++i)  {      // use portfolio variable here.  }  


Solution:2

There is an array in your object. I believe you're looking for this:

var portfolios = jsonObject.artist.portfolios[0].entry;  


Solution:3

The portfolios property is an array, so you need to use an index to get the first element:

var portfolios = jsonObject.artist.portfolios[0].entry;  

Note:If u also have question or solution just comment us below or mail us on toontricks1994@gmail.com
Previous
Next Post »