Python Forum

Full Version: read json string as dict
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,

I am trying to decode the string as dict.

>>> json_string
'{"ip": "13.1.6.0","data": {"tls": {"status": "io-timeout","protocol": "tls","timestamp": "2019-05-08T16:02:43+05:30","e
rror": "EOF"}}}{"ip": "13.1.6.0","data": {"tls": {"status": "unknown-error","protocol": "tls","timestamp": "2019-05-08T16:0
2:43+05:30","error": "tls: oversized record received with length 20527"}}}{"ip": "13.1.6.1","data": {"tls": {"status":
 "io-timeout","protocol": "tls","timestamp": "2019-05-08T16:02:43+05:30","error": "read tcp 13.1.6.0:60812-\\u003e13.1.6.0:443: read: connection reset by peer"}}}'
How can i decode the above string such that i can access like json_string["ip"], json_string["ip"]["tls"]

I tried using json.dumps as seen below

json_data = json.dumps(json_string)
>>> json_data["ip"]
Traceback (most recent call last):
  File "<input>", line 1, in <module>
    json_data["ip"]
TypeError: string indices must be integers, not str
please help. Sad
sorry, there was a problem with my json format while reading content from file. thanks for pointing out.
(May-08-2019, 12:50 PM)goron Wrote: [ -> ]sorry, there was a problem with my json format while reading content from file. thanks for pointing out.
if reading from file, why do you read in string? load directly from file into json_data.


import json

with open('sample.json') as json_file:
    json_data = json.load(json_file)

print(json_data)
Also, back to your snippet, when convert from string to json object json_data you would use json.loads(), not json.dumps()