使用 JSON 文件和 Javascript

发布于 2024-10-02 02:23:04 字数 2671 浏览 0 评论 0 原文

返回 JSON 文件时,我似乎无法检测返回了多少结果。问题似乎在于 JSON 文件每次返回不同数量的项目。有时它会返回 1 个项目,有时它会返回超过 1 个项目。您看,我正在尝试从 JSON 文件获取第一个结果,以便可以显示它。现在,如果每次我知道将返回的数字时更改代码,则以下两位代码将起作用。Artists.id;和 Artists.id[0];,但目前我似乎无法让它们一起工作。

如果返回 1 结果,Artists.id;将成功取回艺术家ID;
如果返回多于1个结果Artists.id;将返回“未定义”。

所以我需要将其更改为Artists.id[0];如果 JSON 文件返回超过 1 项。但是,当我将其更改为此时,如果 JSON 包含 1 项,它将返回“未定义”。

看来我需要一些代码来告诉我返回的数组是否有 1 个或多个项目。我已经尝试过 arr.length 但这似乎不起作用(也许我错误编码了它)。我也尝试过 if(arr===undefined) ,但也失败了。下面的代码是我使用artistzero想出的,但它不起作用。有人有什么建议吗?或者下面的代码不起作用的原因?

当前代码:

    $.ajax(
    {
        type: "GET",
        url: id_url,
        dataType: "jsonp",
        success: function (responseData, textStatus, XMLHttpRequest)
        {
            if (responseData.Artists.Artist)
            {
                var Artists = responseData.Artists.Artist;
                var artistzero = Artists.length;

                if (artistzero >= 2)
                {
                    // if more than one result is returned
                    var artisttype = Artists.id[0];
                }
                if (artistzero <= 1)
                {
                    // if one result is returned
                    var artisttype = Artists.id;
                }
            }
            else
            {
                $('body').append('No results');
            }
        }
    });

具有 1 个结果的示例 JSON:

{"Artists":{"total":"1","count":"1","start":"1","errorCount":"0","Artist":{"id":"33291476","flags":"123010","catzillaID":"0","website":"","name":"Jamie T","rating":"-1","ItemInfo":{"Relevancy":{"index":"1316"}},"hotzillaID":"1809709440","url":"http://web.com/jamie-t/","trackCount":"96"}}}

具有多个结果的示例 JSON:

{"Artists":{"total":"1087","count":"3","start":"1","errorCount":"0","Artist":[{"id":"256212","flags":"123523","catzillaID":"1927205428","website":"http://www.bobmarley.com/","name":"Bob Marley","rating":"-1","ItemInfo":{"Relevancy":{"index":"718"}},"hotzillaID":"1802045595","url":"http://web.com/bob-marley/","trackCount":"12706"},{"id":"312874","flags":"124611","catzillaID":"1927580000","website":"http://www.bobdylan.com/","name":"Bob Dylan","rating":"-1","ItemInfo":{"Relevancy":{"index":"694"}},"hotzillaID":"1800021697","url":"http://web.com/bob-dylan/","trackCount":"4987"},{"id":"268472","flags":"41603","catzillaID":"1927193413","website":"","name":"Bob Wills","rating":"-1","ItemInfo":{"Relevancy":{"index":"644"}},"hotzillaID":"1800264434","url":"http://web.com/bob-wills/","trackCount":"2364"}]}}

On return of a JSON file I can't seem to be able to detect how many results are returned. The problem seems to be with the JSON file returning a diffrent number of items each time. At times it will return 1 item, then at other it will return more than 1. You see, I'm trying to get the very first result from the JSON file so I can display it. Now, If change the code everytime I know the number that will be returned, the following two bits of code work.. Artists.id; and Artists.id[0];, but I can't seem to make them work together, at the momment..

If 1 result is returned, Artists.id; will successfully bring back the artist ID;
If more than 1 result is returned Artists.id; will return "undefined".

So I need to change it to Artists.id[0]; if the JSON file returns more than 1 item. However when I change it to this, if the JSON conatins 1 item, it will return "undefined".

It seems I need some code to tell me if the returned array has 1 or more items. I've tried arr.length but that doesn't seem to be working (perhaps i miss-coded it). I also tried if(arr===undefined) and that failed to work too. The code below is what I have come up with, using the artistzero, but it is not working. Anyone has any advice? or a reason why the code below would not work?

Current Code:

    $.ajax(
    {
        type: "GET",
        url: id_url,
        dataType: "jsonp",
        success: function (responseData, textStatus, XMLHttpRequest)
        {
            if (responseData.Artists.Artist)
            {
                var Artists = responseData.Artists.Artist;
                var artistzero = Artists.length;

                if (artistzero >= 2)
                {
                    // if more than one result is returned
                    var artisttype = Artists.id[0];
                }
                if (artistzero <= 1)
                {
                    // if one result is returned
                    var artisttype = Artists.id;
                }
            }
            else
            {
                $('body').append('No results');
            }
        }
    });

Sample JSON with 1 result:

{"Artists":{"total":"1","count":"1","start":"1","errorCount":"0","Artist":{"id":"33291476","flags":"123010","catzillaID":"0","website":"","name":"Jamie T","rating":"-1","ItemInfo":{"Relevancy":{"index":"1316"}},"hotzillaID":"1809709440","url":"http://web.com/jamie-t/","trackCount":"96"}}}

Sample JSON with more than one result:

{"Artists":{"total":"1087","count":"3","start":"1","errorCount":"0","Artist":[{"id":"256212","flags":"123523","catzillaID":"1927205428","website":"http://www.bobmarley.com/","name":"Bob Marley","rating":"-1","ItemInfo":{"Relevancy":{"index":"718"}},"hotzillaID":"1802045595","url":"http://web.com/bob-marley/","trackCount":"12706"},{"id":"312874","flags":"124611","catzillaID":"1927580000","website":"http://www.bobdylan.com/","name":"Bob Dylan","rating":"-1","ItemInfo":{"Relevancy":{"index":"694"}},"hotzillaID":"1800021697","url":"http://web.com/bob-dylan/","trackCount":"4987"},{"id":"268472","flags":"41603","catzillaID":"1927193413","website":"","name":"Bob Wills","rating":"-1","ItemInfo":{"Relevancy":{"index":"644"}},"hotzillaID":"1800264434","url":"http://web.com/bob-wills/","trackCount":"2364"}]}}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(4

染柒℉ 2024-10-09 02:23:04

您需要先访问第一位艺术家,然后再获取 id (因为它是一个数组),如下所示:

var artisttype = Artists[0].id;

如果您可以将 JSON 更改为始终返回一个数组,那就更好了,即使有一个结果......不幸的是,有些平台不这样做,原因超出了我的理解。

You need to access the first artist before grabbing the id (since it's an array) like this:

var artisttype = Artists[0].id;

It would be better if you could change the JSON to always return an Array, even with one result...unfortunately some platforms don't do this, for reasons beyond my comprehension.

好久不见√ 2024-10-09 02:23:04
 for(var propertyname in responseData){
       //will loop through the different elements in your json array
      alert(responseData[propertyName]); //will output the valueof each element
}
 for(var propertyname in responseData){
       //will loop through the different elements in your json array
      alert(responseData[propertyName]); //will output the valueof each element
}
焚却相思 2024-10-09 02:23:04

你说得对,这是有问题的,而且说实话,听起来向你发送 JSON 的“另一端”不一致。

问题是,当有多个项目时,他们会向您发送 id 属性的数组,而当有单个项目时,他们只会向您发送一个简单的值(例如整数)。理想情况下,当有单个项目时,您应该收到一个单项目数组 - 这将让您每次都使用相同的基于数组的解析代码。

但是,如果您无法说服他们更改发送给您的内容,那么最好的选择就是做您当前正在做的事情;查看 Artists.id 是否已定义,如果已定义,则使用它,否则返回以数组形式访问 id

You're right that this is problematic, and to be honest it sounds like the "other end" that's sending you the JSON is being inconsistent.

The problem is that when there are multiple items they're sending you an array for the id property, and when there's a single item they're just sending you a simple value (e.g. an integer). Ideally, when there is a single item you should be sent a single-item array - this would let you use the same array-based parsing code every time.

If you can't convince them to change what they're sending you, though, then the best bet is simply to do what you're currently doing; see if Artists.id is defined, use it if so, else fall back to accessing id as an array.

浮华 2024-10-09 02:23:04

但是,如果返回多于1个结果Artists.id;将返回“未定义”。所以我需要将其更改为:Artists.id[0];

如果 Artists.id[0] 存在,这不能是 Artists.id 应该是“对象”而不是未定义。也许是如 Artists[0].id 所说?如果是这样,你可以测试 typeof(Artists) == typeof([])

However, if more than 1 result is returned Artists.id; will return "undefined". So I need to change it to this: Artists.id[0];

this cannot be Artists.id should be "object" not undefined if Artists.id[0] exists. Maybe it is as stated Artists[0].id ? and if so you could test typeof(Artists) == typeof([])

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文