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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/20777173/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 21:12:56  来源:igfitidea点击:

Add variable value in a JSON string in Python

pythonjson

提问by

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.

我很困惑为什么这不起作用。我正在尝试在 JSON 中添加我的变量值,每次添加它时,它都没有在我的 JSON 字符串中正确显示。

hostname = "machineA.host.com"

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

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

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?

不确定我在这里做错了什么?

采纳答案by Peter Gibson

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

在 python 中,您还可以'对字符串使用单引号- 并且您不需要在单引号字符串中转义双引号

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 JSONmodule by converting a python dictto a JSON string

接下来是使用 Python JSON模块,将 pythondict转换为 JSON 字符串

>>> 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.

这可能是首选方法,因为它将处理转义主机名和其他字段中的奇怪字符,确保最后有有效的 JSON。

Is there a reason you're using a bytestring

您是否有理由使用 bytestring

回答by Guy Gavriely

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

与其操作字符串,不如考虑将数据作为 python 结构,然后将其转储到 json

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