Tag Archives: string

JavaScript: Convert string into a XML object

Here is a small function in JavaScript, which converts a string into a XML object.

function StringToXML(text) {
    if (window.ActiveXObject) {
        var doc = new ActiveXObject('Microsoft.XMLDOM');
	doc.async = 'false';
	doc.loadXML(text);
    } else {
        var parser = new DOMParser();
	var doc = parser.parseFromString(text, 'text/xml')
    }
    return doc;
}
Advertisements
Tagged , ,

Convert a string to a list in Python

I use web.py as the framework of a website project. Recently I developed an iPhone app as the client of the website. The app use POST method to send accelerometer data to the website, and when the web.py receive the data:

class sensor:
    def POST(self):
    data = web.data()
    print data

And the data is like this:

[["accelerometer",1303884181462.097,0.1742249,-0.6092377,-0.7658691],["accelerometer",1303884181562.537,0.1266632,-0.5593719,-0.8358765],["accelerometer",1303884181663.125,0.1494141,-0.5847778,-0.7957916],["accelerometer",1303884181763.665,0.1268768,-0.572403,-0.8113861],["accelerometer",1303884181864.305,0.1513062,-0.5777588,-0.7967834],["accelerometer",1303884181964.956,0.1298676,-0.5714264,-0.8062439],["accelerometer",1303884182065.627,0.1447754,-0.5565643,-0.8131866],["accelerometer",1303884182166.559,0.1371918,-0.5825806,-0.7959442],["accelerometer",1303884182266.844,0.1352997,-0.5885773,-0.7918701],["accelerometer",1303884182367.435,0.1406708,-0.6017303,-0.7897797]]

However, when I thought it was a list and try to get data[i], I found that it was

data[0] = '['
data[1] = '['
data[2] = '"'

which means, it is a string, not a list.

I searched online for a solution to convert a string to a list, someone suggested we use string = string[1:-1].split(',') or something. It was a lot of dirty work for my example. Finally, I found an elegant solution for this problem:

list_data = eval(data)

Just as simple as this! Now I can type

for entries in list_data:
    print entries

and get

["accelerometer",1303884181462.097,0.1742249,-0.6092377,-0.7658691]

Of course, the entries itself now is a list, too! 😀

Tagged , ,