2

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

<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?

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

Mickael Lherminez
  • 862
  • 1
  • 7
  • 24
balint
  • 3,251
  • 6
  • 38
  • 48

7 Answers7

5

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

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

Joel Coehoorn
  • 362,140
  • 107
  • 528
  • 764
  • it's true, it's magically JSONified by the webservice; but in JS, I only see [Object object] :) – balint Apr 15 '09 at 15:47
  • The [Object object] is your data -- you can access it as you would an array. – btk Jul 24 '10 at 03:47
2

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:

   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()
      });
cgp
  • 39,478
  • 10
  • 96
  • 129
2
var array = eval(json.d);

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

stevehipwell
  • 48,850
  • 5
  • 42
  • 60
2

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

Object.fromXML(yourXMLObject)

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

{
  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;
};
BYK
  • 1,341
  • 1
  • 13
  • 30
0

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):

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

Works in Firefox 15.0.1

The jQuery way is:

 newArray = $.parseJSON(JSONstring);
Alexx Roche
  • 2,654
  • 1
  • 29
  • 38
0

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

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

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

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

Seb
  • 24,063
  • 5
  • 57
  • 82
0

If you've told explicitly jQuery that you're expecting an XML document back (using the dataType option) 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 responseXML instead 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 data is an XML document:

$(data).find("ArrayOfString").map(function()
{
    return $(this).find('string').map(function()
    {
        return $(this).text();
    });
});
Jonny Buchanan
  • 58,371
  • 16
  • 137
  • 146