带有 JSON 数组的 Jquery - 转换为 Javascript 数组

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/752222/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-26 09:43:50  来源:igfitidea点击:

Jquery with JSON Array - convert to Javascript Array

jqueryarraysjsonxml

提问by balint

I've the following XML output from an asp.net webservice:

我有以下来自 asp.net 网络服务的 XML 输出:

<ArrayOfArrayOfString>
    <ArrayOfString>
        <string>1710</string>
        <string>1711</string>
        <string>1712</string>
        <string>1713</string>
    </ArrayOfString>
    <ArrayOfString>
        <string>Teleszkóp 350mm gázas</string>
        <string>Teleszkóp 150mm olaj</string>
        <string>Teleszkóp 260mm olaj sárga</string>
        <string>Teleszkóp 260mm els?</string>
    </ArrayOfString>
</ArrayOfArrayOfString>

I'm using JQuery's $Ajax to get it from the server, it works fine. It's converted to a JSON object, but how can I convert it back to a Javascript Array?

我正在使用 JQuery 的 $Ajax 从服务器获取它,它工作正常。它已转换为 JSON 对象,但如何将其转换回 Javascript 数组?

update: the problem is, if it's parsed with eval(), this Array-in-Array becomes one string only!

更新:问题是,如果用 eval() 解析它,这个 Array-in-Array 就变成了一个字符串!

回答by Joel Coehoorn

That's not a JSON object: it's xml. JSON essentially isjavascript, and would look more like this:

那不是 JSON 对象:它是 xml。JSON 本质上javascript,看起来更像这样:

[["1710", "1711", "1712","1713"], ["Teleszkóp 350mm gázas", "Teleszkóp 150mm olaj", "Teleszkóp 260mm olaj sárga", "Teleszkóp 260mm els?"]]

[[“1710”,“1711”,“1712”,“1713”],[“Teleszkóp 350mm gázas”,“Teleszkóp 150mm olaj”,“Teleszkóp 260mm olaj sárga”,“Teleszkóp”]?

回答by cgp

I assume your data is coming back and being parsed automagically by jQuery and put into an XML Document. This is one way to flatten the XML object into an array:

我假设您的数据正在返回并由 jQuery 自动解析并放入 XML 文档中。这是将 XML 对象展平为数组的一种方法:

   my parsedData = [];  
   $('result', data).each(function() {
      parsedData.push(  
         { name: $('name', this).text(),
           addr: $('addr', this).text(),
           city: $('city', this).text(),
           state: $('state', this).text(),
           zip: $('zip', this).text()
      });

回答by stevehipwell

var array = eval(json.d);

Where array is the javascript array and json is the json object and json.d is the json string.

其中 array 是 javascript 数组, json 是 json 对象, json.d 是 json 字符串。

回答by BYK

Well here's a code that I have written to convert an XML object to a native JavaScript object(arrays included). You just need to call

好吧,这是我编写的用于将 XML 对象转换为原生 JavaScript 对象(包括数组)的代码。你只需要打电话

Object.fromXML(yourXMLObject)

And you'll get a native JavaScript object whose JSON equivalent is this:

你会得到一个原生的 JavaScript 对象,它的 JSON 等价物是这样的:

{
  ArrayOfString:
  [
    {string: ['1710', '1711', '1712', '1713']},
    {string: ['Teleszkóp 350mm gázas', 'Teleszkóp 150mm olaj', 'Teleszkóp 260mm olaj sárga', 'Teleszkóp 260mm els?']}
  ]
}

The function's source is below.

该函数的来源如下。

/**
 * Tries to convert a given XML data to a native JavaScript object by traversing the DOM tree.
 * If a string is given, it first tries to create an XMLDomElement from the given string.
 * 
 * @param {XMLDomElement|String} source The XML string or the XMLDomElement prefreably which containts the necessary data for the object.
 * @param {Boolean} [includeRoot] Whether the "required" main container node should be a part of the resultant object or not.
 * @return {Object} The native JavaScript object which is contructed from the given XML data or false if any error occured.
 */
Object.fromXML=function(source, includeRoot)
{
    if (typeof source=='string')
    {
        try
        {
            if (window.DOMParser)
                source=(new DOMParser()).parseFromString(source, "application/xml");
            else if (window.ActiveXObject)
            {
                var xmlObject=new ActiveXObject("Microsoft.XMLDOM");
                xmlObject.async=false;
                xmlObject.loadXML(source);
                source=xmlObject;
                xmlObject=undefined;
            }
            else
                throw new Error("Cannot find an XML parser!");
        }
        catch(error)
        {
            return false;
        }
    }
    var result={};
    if (source.nodeType==9)
        source=source.firstChild;
    if (!includeRoot)
        source=source.firstChild;

    while (source) 
    {
        if (source.childNodes.length) 
        {
            if (source.tagName in result) 
            {
                if (result[source.tagName].constructor != Array) 
                    result[source.tagName] = [result[source.tagName]];
                result[source.tagName].push(Object.fromXML(source));
            }
            else 
                result[source.tagName] = Object.fromXML(source);
        }
        else if (source.tagName)
            result[source.tagName] = source.nodeValue;
        else
            result = source.nodeValue;
        source = source.nextSibling;
    }

    return result;
};

回答by Jonny Buchanan

If you've told explicitly jQuery that you're expecting an XML document back (using the dataTypeoption) or if you haven't specified the data type and the server is sending it correctly as XML anyway (in which case, jQuery will guess and give you back responseXMLinstead of responseText), you should be able to use the following in your success callback function to extract an Array of Arrays of Strings from the XML, where datais an XML document:

如果你已经明确告诉 jQuery 你期待返回一个 XML 文档(使用dataType选项),或者如果你没有指定数据类型并且服务器无论如何都将它作为 XML 正确发送(在这种情况下,jQuery 会猜测并给你responseXML而不是responseText),你应该能够在你的成功回调函数中使用以下内容从 XML 中提取一个字符串数组,其中data是一个 XML 文档:

$(data).find("ArrayOfString").map(function()
{
    return $(this).find('string').map(function()
    {
        return $(this).text();
    });
});

回答by Alexx Roche

Your question seems to not match well with its title, but having read it a few times I think that answer would be, (in javascript):

您的问题似乎与其标题不太匹配,但读过几次后,我认为答案是,(在 javascript 中):

var JSONstring = '{"something":"like this"}';
var newArray = JSON.parse(JSONstring);

Works in Firefox 15.0.1

适用于 Firefox 15.0.1

The jQuery way is:

jQuery的方式是:

 newArray = $.parseJSON(JSONstring);

回答by Seb

If it were JSON, you wouldn't need to convert anything... e.g.:

如果是JSON,则不需要转换任何内容...例如:

var jsonString = ".....";
var converted = eval(jsonString);

JSON means JavaScript Object Notation, so whatever is in JSON format works directly in JavaScript.

JSON 表示 JavaScript 对象表示法,因此 JSON 格式的任何内容都可以直接在 JavaScript 中使用。

What you have there is XML. You should go over it and convert to JavaScript manually.

您拥有的是 XML。您应该检查它并手动转换为 JavaScript。