python - python中的json列表操作
问题描述
关于 Json 列表操作的快速问题。
我有以下格式的 json 数据
[
"fruits",
"apple",
"{\n \"color\": \"red\",\n \"harvest\": \"ready\"\n}\n",
"{\n \"color\": \"green\",\n \"harvest\": \"not ready\"\n}\n",
"veggies",
"spinach"
"{\n \"color\": \"green\",\n \"harvest\": \"not ready\"\n}\n",
"{\n \"color\": \"light green\",\n \"harvest\": \"not ready\"\n}\n"
]
我想将“{”之前的任何字符串(例如:apple and spinach)带入“Key-Value”并在json中添加一个静态“keys”,如“name”和“features”,最后它看起来像这:
{
"fruits":{"name":"apple",
"features":[
{
"color":"red",
"harvest":"ready"
}",
{"color":"green"
"harvest":"not ready"
]},
"veggies":{"name":"spinach",
"features":[
{
"color":"green",
"harvest":"notready"
},
{
"color":"light green",
"harvest":"not ready"
]}
}
解决方案
一些建议可以为您提供如何进行的想法:
使用您提供的字符串列表(我认为在 之后缺少一个逗号"spinach"
)
strings = [
"fruits",
"apple",
"{\n \"color\": \"red\",\n \"harvest\": \"ready\"\n}\n",
"{\n \"color\": \"green\",\n \"harvest\": \"not ready\"\n}\n",
"veggies",
"spinach",
"{\n \"color\": \"green\",\n \"harvest\": \"not ready\"\n}\n",
"{\n \"color\": \"light green\",\n \"harvest\": \"not ready\"\n}\n"
]
这
import json
items = []
for string in strings:
try:
items.append(json.loads(string))
except:
items.append(string)
为您提供 ( print(items)
) 以下列表:
['fruits',
'apple',
{'color': 'red', 'harvest': 'ready'},
{'color': 'green', 'harvest': 'not ready'},
'veggies',
'spinach',
{'color': 'green', 'harvest': 'not ready'},
{'color': 'light green', 'harvest': 'not ready'}]
现在这个然后
results = {}
items = iter(items)
while True:
try:
category = next(items)
except StopIteration:
break
results[category] = {
'name': next(items),
'features': [next(items), next(items)]
}
产生 ( print(results)
)
{'fruits': {'features': [{'color': 'red', 'harvest': 'ready'},
{'color': 'green', 'harvest': 'not ready'}],
'name': 'apple'},
'veggies': {'features': [{'color': 'green', 'harvest': 'not ready'},
{'color': 'light green', 'harvest': 'not ready'}],
'name': 'spinach'}}
到目前为止,一切都很好,但我怀疑您的字符串列表实际上更长。它很可能包含必须包含在结果中的其他水果或蔬菜。为此,您需要相应地调整程序的结构(包括结果的结构)。
推荐阅读
- javascript - Socket io + node + json 实例崩溃
- excel - 如何通过 VBA 为链接值添加或减去数字?
- python - 使用 Beautiful Soup 提取多个表和标题
- python - 使用 get-pip.py 安装 pip 时权限被拒绝
- c# - 另一个外键属性旁边的 EF Core 一对多关系
- list - 如何在某个位置获取列表中某个项目的值?
- python - 如何检测python列表中是否存在'\ n'?
- asp.net-core - 如何从 ActionFilter 中识别模型并将 json 数据绑定到该模型
- amazon-cloudformation - Cloudformation 模板验证器
- windows - Electron:在图标上拖放文件