[英]Using json.dumps(string) to dump a string
I want to put string into json.dumps() 我想将字符串放入json.dumps()
string = "{data}"
print json.dumps(string)
And I get: 我得到:
"{data}"
instead of: {data}
"{data}"
而不是: {data}
How I can get this string without quotes? 我如何获得不带引号的字符串?
Method replace
: 方法
replace
:
json.dumps(string.replace('"', '')
or strip
: 或
strip
:
json.dumps(string.strip('"')
Does not work. 不起作用。
You don't dump a string but to a string. 你不倾倒的字符串,而是一个字符串。
d = {"foo": "bar"}
j = json.dumps(d)
print(j)
Output: 输出:
{"foo": "bar"}
It makes no sense to use a string as the argument of json.dumps
which is expecting a dictionary or a list/tuple as the argument. 使用字符串作为
json.dumps
的参数(使用字典或列表/元组作为参数)是没有意义的。
Serialize
obj
to a JSON formatted str using this conversion table.使用此转换表将
obj
序列obj
JSON格式的str。
In [17]: d = {"foo": "bar"}
In [18]: j = json.dumps(d)
In [19]: j
Out[19]: '{"foo": "bar"}'
Now if you need your dictionary back instead of a string 现在,如果您需要返回字典而不是字符串
In [37]: l=json.loads(j)
In [38]: l
Out[38]: {u'foo': u'bar'}
or alternatively 或者
In [20]: import ast
In [22]: k=ast.literal_eval(j)
In [23]: k
Out[23]: {'foo': 'bar'}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.