简体   繁体   中英

Convert Python string to array in JavaScript

I have a JavaScript script which receives information from a Python server. The Python server outputs a list, which is converted to a string prior to being sent to the JavaScript script.

I'd like to be able to convert the received string into a form that can be indexed with JavaScript. Here's an example output string from the Python server:

var Message = [['Word1A', 'Word1B'], ['Word2A', 'Word2B'], ['Word3A', 'Word3B']];

Given the above example, I'd like to be able to query the received string as as an indexed array:

var x;
for (x in Message) {
    alert(x[0]};

The above example should return:

Word1A
Word2A
Word3A

What's the best way to go about this?

You can simply use the json Python module

reply = json.dumps(Message)

to convert the array in a JSON formatted string.

Then on the client side you decode the JSON string with

message = JSON.parse(msg);

and you will get an array of 2-elements arrays

This should work,

var Message = [['Word1A', 'Word1B'], ['Word2A', 'Word2B'], ['Word3A', 'Word3B']];
var x;
for (x in Message) {
    alert(Message[x][0]);
}

Editing my answer as per you comments below which says the input would be "['Word1A', 'Word1B'], ['Word2A', 'Word2B'], ['Word3A', 'Word3B']"

Solution being,

var Message = "['Word1A', 'Word1B'], ['Word2A', 'Word2B'], ['Word3A', 'Word3B']";
var array = Message.replace(/,|[|]/g, "").split(" ");
for(var x = 0; x < array.length -1; x=x+2){
 alert(array[x].replace("[","").replace("]",""));
}

I must add, this solution will work but I'm not that fluent with regex, so more optimal solution could be achieved. Hope it helps!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM