我有以下数据字符串:
{"responseStatus":"ok","responseHeader":{"now":1528734419187,"status":"ok","requestId":"Wx6i0wquZS4AAFNeStwAAABg"},"responseData":{"id":38}}
我需要从中取出" id":38并将其格式化为" id":" 38"
答案 0 :(得分:2)
由于您使用的是requests
库(基于您的代码),因此在调用您的repsonse时,您可以返回.content
而不是返回.json()
:
response = requests.get(....).json()
response['responseData']['id'] = str(response['responseData']['id']) # or you can just do "38"
答案 1 :(得分:0)
您可以使用json
模块:
import json
json_s = json.loads('{"responseStatus":"ok","responseHeader":{"now":1528734419187,"status":"ok","requestId":"Wx6i0wquZS4AAFNeStwAAABg"},"responseData":{"id":38}}')
json_s['responseData']['id'] = '38' # Or str(json_s['responseData']['id'])
print(json_s)
或者在这种情况下,它是一个有效的字典,因此您可以使用eval()
:
json_s = '{"responseStatus":"ok","responseHeader":{"now":1528734419187,"status":"ok","requestId":"Wx6i0wquZS4AAFNeStwAAABg"},"responseData":{"id":38}}'
a = eval(json_s)
a['responseData']['id'] = '38' # Or str(a['responseData']['id'])
print(a)
如果您想将json_s
和a
中的字典转换回字符串,则只需分别使用str(json_s)
和str(a)
。
有关eval()
的使用,请参阅the documentation。
否则,请远离eval()
使用ast
模块。如下所述:
Convert a String representation of a Dictionary to a dictionary?