[英]Manipulate String to Dictionary and viceversa
Through a http Post using httplib2 I obtain some statistics from a network resource : 通过使用httplib2的http Post,我可以从网络资源中获取一些统计信息:
resp, content = http.request(statistics_url,
method='POST',
headers={'Content-Type': 'application/json', 'charset':'UTF-8','Connection':'keep-alive','Host':'theHost'},
body=json_body)
The " resp
" reveals that I receive back " {'content-type': 'application/json; charset=UTF-8'...
" “
resp
”显示我收到了“ {'content-type': 'application/json; charset=UTF-8'...
“
Checking the type of the content
obj : type(content)
returns str
检查
content
obj的type(content)
: type(content)
返回str
and the format of the content
object is : content
对象的格式为:
{
"key" : "string value"
............
"key" : int value
}
Since I want to augment this with some other data I turn this into a Json object, append to it the data I need and then try to do a string out of it again ( since I need to pass it further) 由于我想用其他一些数据来扩充它,因此将其变成一个Json对象,将所需的数据附加到该对象上,然后尝试再次使用它生成一个字符串(因为我需要进一步传递它)
jdata = json.loads(s)
jdata['ip_address']="some ip address"
v1 = json.dumps(jdata)
v2 = ast.literal_eval(json.dumps(jdata))
v3 = ast.literal_eval(pprint.pformat(jdata)
None of v1,v2,v3
returns the dictionary in the same format as original. v1,v2,v3
均未以与原始格式相同的格式返回字典。 I obtain either formats like {'key' : 'value'} or {u'key' : u'value'}
which leads to undesired results then passing this information down to other entities. 我获得
{'key' : 'value'} or {u'key' : u'value'}
这会导致不良结果,然后将此信息传递给其他实体。
The question is how to obtain the same format as described above ? 问题是如何获得与上述相同的格式?
You can set the indent
named parameter to a number to get pretty-printed results. 您可以将
indent
命名参数设置为数字以获得漂亮的打印结果。 The v1
version is the way to go: v1
版本是解决方法:
import json
s = """
{
"key1": "value1",
"key2": 5
}
"""
jdata = json.loads(s)
jdata['ip_address']="1.2.3.4"
v1 = json.dumps(jdata, indent=2)
print(v1)
""" Prints
{
"key1": "value1",
"key2": 5,
"ip_address": "1.2.3.4"
}
"""
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.