To convert python str data to dict type

Asked 2 years ago, Updated 2 years ago, 20 views

Hi, everyone. While analyzing the data, there is a problem that cannot be solved no matter how much you googled!

In the chord below, Data and data1 are both str types, and the structure looks similar Data can be easily converted to dict using ast Data1 has a 'malformed node or string' error.

I would really appreciate it if you could tell me how to solve it!

Development Environment Python 3.6 win10

//
import ast

data = '{"table":"orderBook10","action":"update","data":[{"symbol":"XBTUSD","asks":[[7746,1112939],[7746.5,254534],[7747,91312],[7747.5,28998],[7748,72282],[7748.5,6216],[7749,8867],[7749.5,723855],[7750,34774],[7750.5,24855]],"timestamp":"2019-06-05T07:07:24.138Z","bids":[[7745.5,20573],[7745,19865],[7744.5,327373],[7744,52957],[7743.5,38961],[7743,78857],[7742.5,23332],[7742,14815],[7741.5,157590],[7741,288256]]}]}'
data1 = '{"table":"order","action":"update","data":[{"orderID":"6f2d7a84-ee8f-4c63-da1a-e7c4a827c2ea","ordStatus":"Filled","workingIndicator":false,"leavesQty":0,"cumQty":100,"avgPx":8010.5,"clOrdID":"","account":257426,"symbol":"XBTUSD","timestamp":"2019-06-12T13:47:54.079Z"}]}'

d = ast.literal_eval(data1)
print(type(d), d)

python

2022-09-22 18:07

1 Answers

It's json data.

The reason why the error occurs while processing with eval is that Python writes False instead of false.

Since it's a json string, what's more accurate than writing literal_val is using json.

import json

d = json.loads(data1)


2022-09-22 18:07

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.