首页 > 解决方案 > 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"
     ]}
    }

标签: pythonarraysjsonsorting

解决方案


一些建议可以为您提供如何进行的想法:

使用您提供的字符串列表(我认为在 之后缺少一个逗号"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'}}

到目前为止,一切都很好,但我怀疑您的字符串列表实际上更长。它很可能包含必须包含在结果中的其他水果或蔬菜。为此,您需要相应地调整程序的结构(包括结果的结构)。


推荐阅读