Home > database >  Python Json value convert to DICT
Python Json value convert to DICT

Time:09-15

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"
  }
]  

CodePudding user response:

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)

CodePudding user response:

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'}]
  • Related