5

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.

0

3 Answers 3

15

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.

Sign up to request clarification or add additional context in comments.

5 Comments

you might want to print j instead of d
If I want the dictionary to convert to a string i might use json.dumps(). But if I already have a string that I can send it to the recipient without json.dumps? Before ensure that the recipient receives it correctly.
If the content of the string is valid JSON you can send it to somebody who expects JSON. But note that {data} is not valid JSON. Check it at jsonlint.com
The question is ambiguous.But as far as i understand after using json.dumps he is getting a string and wants to change it into a dict..
IMHO it would be clearer if you wrote your output like this: '{"foo": "bar"}', the way @Ajay is doing it.
1
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'}

4 Comments

What about json.loads?
by {data} OP means a dict i guess
I still don't understand why you propose to use ast. Why?
"{data}" instead of: {data} he asked his desired output to be like this
0

By string, I take that the string is a valid json string. json.dumps() does not work with a string directly. Use json.loads() to convert a string to dict and then json.dumps() to dump out:

import json
A = '{"name": "Smith", "age": "10"}'
B = json.loads(A)
type(B) # dict
print(json.dumps(B))
{"name": "Smith", "age": "10"}
Or simply:
print( json.dumps(json.loads(A)) or
print( json.dumps(json.loads(A), indent=4) for pretty print

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.