21

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 = "machineA.host.com"

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?

3 Answers 3

31

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 = "machineA.host.com"
>>> data = {'Machine Name': hostname}
>>> json.dumps(data)
'{"Machine Name": "machineA.host.com"}'

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

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

4 Comments

Thanks for suggestion. For bytestring yes, I am using this with Zookeeper so that's why I need to use bytestring.
@Peter Gibson: any idea why the following doesn't work: '{"Machine Name":"{0}"}'.format("yada") Traceback (most recent call last): File "<stdin>", line 1, in <module> KeyError: '"Machine Name"'
@JavaSa sorry, when using .format the outer braces should be doubled up to avoid triggering the format code. '{{"Machine Name":"{0}"}}'.format("yada") I'll fix the above, thanks for pointing it out
using % looks more clean when your json variable is nested and has mutiple elemets like b'{"ResourceRecordSet": {"Name": "%s","AliasTarget": {"HostedZoneId": "%s","DNSName": "%s"}}}' % (var1, var2,...)
9

instead of manipulating the string consider having the data as a python structure and then dump it to json

>>> d = {}
>>> d['Machine Name'] = hostname
>>> json.dumps(d)
'{"Machine Name": "machineA.host.com"}'

Comments

1

Please see this example you will get some idea.

test=f"Your order total is $ 150."

{"Total":"'+test+'"}

2 Comments

As it’s currently written, your answer is unclear. Please edit to add additional details that will help others understand how this addresses the question asked. You can find more information on how to write good answers in the help center.
And note that this question is over 8 years old, with two existing upvoted answers. Are you sure they don't already cover what you are showing here? Please don't repeat answers. See How to Answer.

Your Answer

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