JavaScript 和 json
我正在使用带有 json 库的 javascript 并遇到了一些麻烦。这是我的 json 输出:
{
"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": [""]
}
}]
}]
}
}
在 javascript 中,我尝试像这样访问地图中的条目:
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);
}
但投资组合是“未定义”。这样做的正确方法是什么?
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?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
查看您的 JSON 结果。
portfolios
是一个单元素数组;portfolios[0]
是一个包含单个键entry
的对象,它映射到同时具有string
和的两个对象的数组>utils.Portfolio
键。因此,语法jsonObject.artist.portfolios.entry
将不起作用。相反,您需要jsonObject.artist.portfolios[0].entry
。如果可能的话,我建议更改生成这些 JSON 结果的任何代码,以完全删除间接的
entry
级别,例如:然后您可以使用以下命令访问它:
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 bothstring
andutils.Portfolio
keys. Thus, the syntaxjsonObject.artist.portfolios.entry
will not work. Instead, you wantjsonObject.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:Then you could access it with
您的对象中有一个数组。我相信您正在寻找这个:
There is an array in your object. I believe you're looking for this:
portfolios
属性是一个数组,因此您需要使用索引来获取第一个元素:The
portfolios
property is an array, so you need to use an index to get the first element: