我从JSON文件中以以下格式提取字符串:
"voltages":[[0.001953125,-12.5],[0.00390625,-12.5],[0.005859375,-12.5]...]]
我想将两项的组合转换为字典或元组,以便可以将其写入Excel文件。
我所做的就是尝试使用正则表达式r'(\[\[.*\]\])+'
或来获取数据json.loads
,但随后我对如何将数据转换为字典一无所知。
{"gain":35.6,"signals":{"trigger":31.73,"baseline":-19.402221696199106,"voltages":
[[0.001953125,-12.5],[0.00390625,-12.5],[0.005859375,-12.5],
[0.0078125,-12.5],[0.009765625,-12.5],[0.01171875,-12.5],[0.013671875,-12.5]...]}}
我最终使用以下内容:
with open(filename, "r") as file:
data = json.loads(file.read())
voltages_dict = dict()
for entry in data['signals']['voltages']:
voltages_dict[entry[0]] = entry[1]
test.json
{
"gain": 35.6,
"signals": {
"trigger": 31.73,
"baseline": -19.402221696199106,
"voltages": [[0.001953125, -12.5], [0.00390625, -12.5], [0.005859375, -12.5], [0.0078125, -12.5], [0.009765625, -12.5], [0.01171875, -12.5], [0.013671875, -12.5]]
}
}
from pathlib import Path
import json
# p = Path('test.json') # if in current dir
# p = Path(r'c:\some_path\test.json') # if it's not in the current dir
p = Path.cwd() / 'test.json'
# read the file
with p.open('r', encoding='utf-8') as f:
data = json.loads(f.read())
# extract information
print(data['signals']['voltages'])
[[0.001953125, -12.5],
[0.00390625, -12.5],
[0.005859375, -12.5],
[0.0078125, -12.5],
[0.009765625, -12.5],
[0.01171875, -12.5],
[0.013671875, -12.5]]
# into a dict
voltages_dict = dict()
voltages_dict['voltages'] = data['signals']['voltages']
# if "signals instead of "signals"
with p.open("r") as file:
read_file = file.read()
read_file.replace('"signals', '"signals"')
# add additional fixes
# save file
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句