在Python中的JSON字符串中添加变量值 [英] Add variable value in a JSON string in Python

查看:1739
本文介绍了在Python中的JSON字符串中添加变量值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我很困惑为什么这不起作用.我正在尝试将变量值添加到JSON中,每次添加它时,它都无法在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"

我需要将上面的主机名信息添加到下面的JSON文档中-

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)

在python中,您还可以对字符串使用单引号'-无需在单引号字符串内转义双引号

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)

接下来是使用Python JSON 模块,方法是转换python 转换为JSON字符串

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

这可能是首选方法,因为它将处理主机名和其他字段中的怪异字符,以确保末尾具有有效的JSON.

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.

您使用bytestring

这篇关于在Python中的JSON字符串中添加变量值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆