python字符串中添加变量,在Python中的JSON字符串中添加变量值

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?

解决方案

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值