python-3.x - 将字符串从 JSON 转换为字典或元组
问题描述
我从 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']
格式错误的 JSON
- 尝试修复各种问题
# 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
推荐阅读
- mongodb - 根据在 Mongo Atlas 中创建的索引在前端创建 MongoDB 索引
- android - 状态展开的底片圆角
- ios - 为什么每台机器上的 iOS 模拟器快照都不同
- python - 是否可以使用 Python 来检测 Windows 的系统动态颜色模式(浅色或深色模式)?
- google-sheets - GoogleFinance - 调整后的股票收盘价
- r - dyn.load 中“networkD3”的 R/Docker 加载失败
- javascript - 当用户单击弹出卡上显示的特定卡时如何绑定数据?
- pandas - 如何通过查看另一列来填充一列中的 NaN 值
- wordpress - Wordpress add_rewrite_rule 忽略部分 URL
- git - 多次提交后如何在初始阶段签出功能分支