首页 > 解决方案 > 将字符串从 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]

标签: python-3.x

解决方案


  • 在名为的文件中给出以下内容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

推荐阅读