文本文件到 JSON
Text file to JSON
我正在尝试将文件中的字符串列表转换为某种 JSON 数据格式。
我的 sample.txt 文件包含以下数据:
1234
5678
9765
我想把它转换成下面的形式formated.json:
{
"x": "1234",
"y": "a"
},
{
"x": "5678",
"y": "a"
},
{
"x": "9765",
"y": "a"
}
这是我的代码:
import itertools
import json
with open('sample.txt', 'r') as f_in, open('formated.json', 'w') as f_out:
for x, y in itertools.zip_longest(*[f_in]*2):
record = {
"x": x.strip(),
"y": "a",
}
f_out.write(json.dumps(record, indent=2))
f_out.write(',\n')
此脚本如何从文本文件跳转每一行并输出:
{
"x": "1234",
"y": "a"
},
{
"x": "9765",
"y": "a"
}
但是,我希望我的脚本读取所有行并输出结果。
只使用行内容,不要使用zip
:
import json
result = []
with open('sample.txt', 'r') as f_in:
for line in f_in:
line = line.strip()
if not line:
continue # skip empty lines
result.append({'x': line, 'y': 'a'})
with open('formated.json', 'w') as f_out:
print(json.dumps(result, indent=2))
#f_out.write(json.dumps(result, indent=2))
输出:
[
{
"x": "1234",
"y": "a"
},
{
"x": "5678",
"y": "a"
},
{
"x": "9765",
"y": "a"
}
]
我正在尝试将文件中的字符串列表转换为某种 JSON 数据格式。 我的 sample.txt 文件包含以下数据:
1234
5678
9765
我想把它转换成下面的形式formated.json:
{
"x": "1234",
"y": "a"
},
{
"x": "5678",
"y": "a"
},
{
"x": "9765",
"y": "a"
}
这是我的代码:
import itertools
import json
with open('sample.txt', 'r') as f_in, open('formated.json', 'w') as f_out:
for x, y in itertools.zip_longest(*[f_in]*2):
record = {
"x": x.strip(),
"y": "a",
}
f_out.write(json.dumps(record, indent=2))
f_out.write(',\n')
此脚本如何从文本文件跳转每一行并输出:
{
"x": "1234",
"y": "a"
},
{
"x": "9765",
"y": "a"
}
但是,我希望我的脚本读取所有行并输出结果。
只使用行内容,不要使用zip
:
import json
result = []
with open('sample.txt', 'r') as f_in:
for line in f_in:
line = line.strip()
if not line:
continue # skip empty lines
result.append({'x': line, 'y': 'a'})
with open('formated.json', 'w') as f_out:
print(json.dumps(result, indent=2))
#f_out.write(json.dumps(result, indent=2))
输出:
[
{
"x": "1234",
"y": "a"
},
{
"x": "5678",
"y": "a"
},
{
"x": "9765",
"y": "a"
}
]