简体   繁体   中英

Python Json value convert to DICT

I have the following 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"

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:

>>> [{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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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