user4737714
user4737714

Reputation:

Using json.dumps(string) to dump a string

I want to put string into json.dumps()

string = "{data}"

print json.dumps(string)

And I get:

"{data}" instead of: {data}

How I can get this string without quotes?

Method replace:

json.dumps(string.replace('"', '')

or strip:

json.dumps(string.strip('"')

Does not work.

Upvotes: 5

Views: 26474

Answers (2)

Ajay
Ajay

Reputation: 5347

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'}

Upvotes: 1

user1907906
user1907906

Reputation:

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.

Serialize obj to a JSON formatted str using this conversion table.

Upvotes: 15

Related Questions