balint
balint

Reputation: 3431

Jquery with JSON Array - convert to Javascript Array

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!

Upvotes: 2

Views: 69964

Answers (7)

Alexx Roche
Alexx Roche

Reputation: 3249

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

Upvotes: 0

BYK
BYK

Reputation: 1374

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;
};

Upvotes: 2

Jonny Buchanan
Jonny Buchanan

Reputation: 62793

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

Upvotes: 0

stevehipwell
stevehipwell

Reputation: 57488

var array = eval(json.d);

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

Upvotes: 2

Seb
Seb

Reputation: 25147

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.

Upvotes: 0

Joel Coehoorn
Joel Coehoorn

Reputation: 415630

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ő"]]

Upvotes: 5

cgp
cgp

Reputation: 41381

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

Upvotes: 2

Related Questions