我正在尝试制作一个小代码,它将从excel中获取值并生成一个json文件。除1个问题外,我获得了所需的输出。下面是我的代码
import json
from openpyxl import load_workbook
print("")
path = "output.xlsx"
wb=load_workbook(path)
Sheet1 = wb.active
max_row=Sheet1.max_row
max_column=Sheet1.max_column
for i in range(2, max_column+1):
listing = []
for j in range(2, max_row+1):
dictonery = {}
dictonery["ParameterKey"] = (Sheet1.cell(j,1)).value
dictonery["ParameterValue"] = (Sheet1.cell(j,i)).value
listing.append(dictonery)
print(json.dumps(listing,indent = 4, sort_keys=True))
我要打印的输出(列表):
print(listing)
[{'ParameterKey': 'SGSSNTCode', 'ParameterValue': 'test'}, {'ParameterKey': 'SDSSCustomer', 'ParameterValue': 'testcompany'}, {'ParameterKey': 'OSName', 'ParameterValue': 'Ubuntu 18.04 LTS'}, {'ParameterKey': 'Hostname', 'ParameterValue': 'testhostname'}, {'ParameterKey': 'SubnetId', 'ParameterValue': 'subnet-0b33e'}, {'ParameterKey': 'SecurityGroupIds', 'ParameterValue': 'sg-05c21ea8,sg-063a770507,sg-0c259b8d,sg-026e2d7b5a'}, {'ParameterKey': 'InstanceType', 'ParameterValue': 'm5.large'}, {'ParameterKey': 'KeyPairName', 'ParameterValue': 'TestPair'}, {'ParameterKey': 'RootVolumeSize', 'ParameterValue': '""'}]
直到这里一切都很好 如上所示,最后一个参数值为“”,但 但是当我运行最后一行即print(json.dumps(清单,indent=4,sort_keys=True))时 我得到的最后一个参数值为“\”\”(在输出下面) 下面是打印输出(json.dumps(清单,缩进=4,排序键=True))
print(json.dumps(listing,indent = 4, sort_keys=True))
[
{
"ParameterKey": "SGASSNTCode",
"ParameterValue": "test"
},
{
"ParameterKey": "SGASCustomer",
"ParameterValue": "testcompany"
},
{
"ParameterKey": "OSName",
"ParameterValue": "Ubuntu 18.04 LTS"
},
{
"ParameterKey": "Hostname",
"ParameterValue": "testhostname"
},
{
"ParameterKey": "SubnetId",
"ParameterValue": "subnet-0b33e"
},
{
"ParameterKey": "SecurityGroupIds",
"ParameterValue": "sg-05c21ea8,sg-063a770507,sg-0c259b8d,sg-026e2d7b5a"
},
{
"ParameterKey": "InstanceType",
"ParameterValue": "m5.large"
},
{
"ParameterKey": "KeyPairName",
"ParameterValue": "TestPair"
},
{
"ParameterKey": "RootVolumeSize",
"ParameterValue": "\"\""
}
]
我需要的JSON输出的最后一个参数值仅为“”。能帮我一些吗
方法1:
将
json.dumps()
的值存储在某个变量中。现在.dumps()
返回一个字符串,这样您就可以用引号替换转义字符,只使用引号,然后将变量写入文件方法2:
填充变量
dictionery
时,如果发现值为""
,只需在值中写入""
。不要像你正在做的那样在单引号内写""
。你将不得不为这个做一个检查,但会工作JSON.dumps()
在jsoning时将所有键、值转换为字符串。 要将""
转换为字符串,必须在其前面包含转义字符\
一旦用
json.loads()
加载JSON,就可以返回原始值相关问题 更多 >
编程相关推荐