SSH SSH - 8 months ago 51
JSON Question

Add variable value in a JSON string in Python

I am puzzled why this is not working. I am trying add my variable value in the JSON and everytime I add it, it is not showing properly in my JSON string.

hostname = ""

I need to add the above hostname information to the below JSON document -

b"{\"Machine Name\":\"\"+hostname+\"\"}", None, True)

But whenever I am adding it in the above way, it is not working at all.

Not sure what wrong I am doing here?


You're escaping the inner double quote " in your string. It should be:

b"{\"Machine Name\":\""+hostname+"\"}", None, True)

In python you can also use single quotes ' for strings - and you don't need to escape double quotes inside single quoted strings

b'{"Machine Name":"'+hostname+'"}', None, True)

There are two better ways of doing this though. The first is string formatting which inserts a variable into a string:

b'{"Machine Name":"%s"}' % hostname # python 2.x (old way)
b'{{"Machine Name":"{0}"}}'.format(hostname) # python >= 2.6 (new way - note the double braces at the ends)

The next is with the Python JSON module by converting a python dict to a JSON string

>>> hostname = ""
>>> data = {'Machine Name': hostname}
>>> json.dumps(data)
'{"Machine Name": ""}'

This is probably the preferred method as it will handle escaping weird characters in your hostname and other fields, ensuring that you have valid JSON at the end.

Is there a reason you're using a bytestring