简体   繁体   中英

Convert Python dict to Javascript Object and access the key and value

Trying to access just the value or key of the JSON object but it displays as undefined.

Tried to json.parse but same results.

now = datetime.now()
date_time = now.strftime("%m/%d/%Y, %H:%M:%S")
print(date_time)
chatrooms[chatroom][username][date_time] = message
message = json.dumps(chatrooms[chatroom][username])
emit("append messages", message, broadcast=True)
socket.on('append messages', data => {
             const li = document.createElement('li');
             // parse the messages;
             var response = jQuery.parseJSON(data)
             message = `${response.date_time}`;

The message that was sent in, but I am getting undefined. I tried ridding of the jQuery Parse, but it is not working.

So I finally solved the issue, first you have to use json.dumps(foo) from the python side via socketemit and then to convert it to a Javascript Object - you have to again use json.parse(foo). Then it is in an Object literal which can be accessed using a for loop to get at the value and key! Like so

  for (var i in foo) {
            var key = i;
            var val = foo[i];
}

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