How to get JSON.loads() output in dictionary type but not string type using PYTHON

Mad*_*dhu 5 json python-3.x python-requests python-responses

When I make use of JSON.dump() I am getting below JSON format

Dumps data"b'{\"AutomaticReadabilityIndex\":2.7999999999999994,\"AgeLevel\":[\" 11 to 12\"],\"Statement\":[\"Nice. Your grade is about six\"],\"SpacheScore\":1.877,\"GunningFogScore\":9.099999999999998,\"SmogIndex\":5.999999999999999}'"
Run Code Online (Sandbox Code Playgroud)

When I make use of JSON.loads() I am getting below JSON format with bytes

loads data b'{"AutomaticReadabilityIndex":2.7999999999999994,"AgeLevel":[" 11 to 12"],"Statement":["Nice. Your grade is about six"],"SpacheScore":1.877,"GunningFogScore":9.099999999999998,"SmogIndex":5.999999999999999}'
Run Code Online (Sandbox Code Playgroud)

My question is when I am using loads format the output has to be in dictionary type but I don't know why I am getting string type as my output. How to convert this JSON string into dictionary type.

Loads Data Type : type of loads <class 'str'>
Run Code Online (Sandbox Code Playgroud)

When I trying to parse string type JSON directly I am getting below error

ERROR : Traceback (most recent call last):
File "Db.py", line 84, in <module>
print(par['GunningFogScore'])
TypeError: string indices must be integers
Run Code Online (Sandbox Code Playgroud)

Jea*_*bre 5

我可以简单地重现您的问题:

import json

s = {"AutomaticReadabilityIndex":2.7999999999999994,"AgeLevel":[" 11 to 12"],"Statement":["Nice. Your grade is about six"],"SpacheScore":1.877,"GunningFogScore":9.099999999999998,"SmogIndex":5.999999999999999}

print(json.dumps(json.dumps(s)))
Run Code Online (Sandbox Code Playgroud)

结果:

"{\"SmogIndex\": 5.999999999999999, \"AutomaticReadabilityIndex\": 2.7999999999999994, \"SpacheScore\": 1.877, \"GunningFogScore\": 9.099999999999998, \"AgeLevel\": [\" 11 to 12\"], \"Statement\": [\"Nice. Your grade is about six\"]}"
Run Code Online (Sandbox Code Playgroud)

所以要么:

  • 你正在链接两个转储。第一个dump将字典转换成字符串,但是转储字符串也是有效的,所以对字符串进行转储、引号、转义等等...
  • 你正在转储一个看起来像字典的字符串("{12:1,14:2}")。

(如果您不确定类型,请type(s)在执行转储之前检查)

所以当你重新加载时

par = json.loads(s)
Run Code Online (Sandbox Code Playgroud)

你得到一个字符串,而不是字典,它解释了使用时的错误消息[](因为你试图将键传递给字符串)

解决方法:

用于json.loads(json.loads(s))恢复您的数据。

作为更好的修复方法,只需dumps在序列化过程中使用一次即可。