我需要按此顺序的json文件,因为我必须不断更改json值。 这是我要生成的示例文件
1.control_file json中的位置名称标签也应以“”,“”格式括起来 我需要帮助。
{
"user": "dex",
"issue_no": "test_tkt",
"start_date": "2017-07-01",
"end_date": "2017-07-01",
"geo-ids": [627,438,360],
"location_names": [
"India.v1.2a_Final",
"China.v2.3a_setup",
"Hongkong.4a"
]
}
下面是我写的代码。 预期的输出
import json
import os
filename = input("Enter the file name: ")
user = input("Enter the user name: ")
ticket = input("Enter the ticket id: ")
start_date = input("Enter the start date: ")
end_date = input("Enter the end date: ")
test_list=[]
input_list=input("enter the exp names: ")
exports = input_list.split(",")
for names in exports:
demo = test_list.append(names)
print(demo)
if not os.path.splitext(filename)[1]:
filename += ".txt"
with open(filename, 'w') as f:
json.dump({
"user": user,
"ticket": ticket,
"start_date": start_date,
"end_date" : end_date,
"location_names" : [demo]
}, f, indent=4)
print("JSON saved to file {}".format(os.path.abspath(filename)))
我得到的输出
{
"user": "dex",
"ticket": "test_tkt",
"start_date": "2017-07-01",
"end_date": "2017-07-01",
"location_names": [
None
None
None
]
}
我想要的输出:
{
"user": "dex",
"issue_no": "test_tkt",
"start_date": "2017-07-01",
"end_date": "2017-07-01",
"location_names": [
"India.v1.2a_Final",
"China.v2.3a_setup",
"Hongkong.4a"
]
}
答案 0 :(得分:2)
您正在将test_list.append()
的返回值分配给变量demo
,但这将始终为None,因为append()
不会返回任何内容。
由于test_list
包含名称列表,因此应将其用作值并删除demo
变量:
with open(filename, 'w') as f:
json.dump({
"user": user,
"ticket": ticket,
"start_date": start_date,
"end_date" : end_date,
"location_names" : test_list # Use test_list
}, f, indent=4)
答案 1 :(得分:0)
改用它。
with open(filename, 'w') as f:
json.dump({
"user": user,
"ticket": ticket,
"start_date": start_date,
"end_date" : end_date,
"location_names" : [item for item in demo]
}, f, indent=4)