简体   繁体   English

Python Json 值转换为 DICT

[英]Python Json value convert to DICT

I have the following json.我有以下 json。

[
  {
    "TX_ID": "C592096166066790609734",
    "FEE_1": 0.25,
    "FEE_7": 0.95,
    "USAGE": "Yzua12"
  },
  {
    "TX_ID": "C636460166108115381222",
    "FEE_1": 0.35,
    "FEE_3": 1.39,
    "USAGE": "Yzua13"
  }
]

Using python, I need the below output value "Fee_* " with dict type with an exception to fields "TX_ID" and "USAGE"使用 python,我需要以下 output 值“Fee_*”,dict 类型,字段“TX_ID”和“USAGE”除外

Expected Result:预期结果:

[
  {
    "TX_ID": "C592096166066790609734",
    "FEE_1": {"set":0.25},
    "FEE_7": {"set":0.95},
    "USAGE": "Yzua12"
  },
  {
    "TX_ID": "C636460166108115381222",
    "FEE_1": {"set":0.35},
    "FEE_3": {"set":1.39},
    "USAGE": "Yzua13"
  }
]  

Once you have the original dict parsed from the JSON, you can use a simple nested list- and dict-comprehension wrapping all those FEE_ values:从 JSON 解析出原始字典后,您可以使用简单的嵌套列表和字典理解来包装所有这些FEE_值:

>>> [{k: {"set": v} if k.startswith("FEE_") else v for k, v in d.items()} for d in original]
[{'TX_ID': 'C592096166066790609734',
  'FEE_1': {'set': 0.25},
  'FEE_7': {'set': 0.95},
  'USAGE': 'Yzua12'},
 {'TX_ID': 'C636460166108115381222',
  'FEE_1': {'set': 0.35},
  'FEE_3': {'set': 1.39},
  'USAGE': 'Yzua13'}]
bt=[
  {
    "TX_ID": "C592096166066790609734",
    "FEE_1": 0.25,
    "FEE_7": 0.95,
    "USAGE": "Yzua12"
  },
  {
    "TX_ID": "C636460166108115381222",
    "FEE_1": 0.35,
    "FEE_3": 1.39,
    "USAGE": "Yzua13"
  }
]
for item in bt:
    # now song is a dictionary
    for attribute, value in item.items():
        if 'FEE' in attribute :
            item[attribute] ={"set":value}
print(bt)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM