views:

17608

answers:

6

Hi, 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!

A: 

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()
      });
altCognito
+3  A: 

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
it's true, it's magically JSONified by the webservice; but in JS, I only see [Object object] :)
balint
The [Object object] is your data -- you can access it as you would an array.
btk
A: 

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
A: 
var array = eval(json.d);

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

Stevo3000
it's not that easy:var arr = eval(response.d);alert(arr[1]); -->> this gets back the whole array, not the 2nd item!
balint
It's a 2-d array! try: alert(arr[1][1]);
Joel Coehoorn
oh, F*! You're right I overlooked, thanks!!!!
balint
@balint - I take it that it works when using it as a 2D array?
Stevo3000
@Stevo3000: exactly!
balint
+2  A: 

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

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();
    });
});
insin