开发者

javascript and json

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?


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.
}


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

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


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;
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜