Home > Back-end >  How to replace certain keys and values of a json with list in python
How to replace certain keys and values of a json with list in python

Time:10-13

{'Functions': {0: {'Function-1': {0: {'Function': 'dd', 'Function2': 'd3'}}}}}

From the above json i would like to remove the {0: } item and add a list in that place so that the value is enclosed in a list like shown in Desired Output.

Please note the above json is an put of a jsondiff.

Desired output

{"Functions":[{"Function-1":[{"Function":"dd","Function2":"d3"}]}]}

The below is my current code :


from jsondiff import diff
json1 = json.loads("""
{
  "Name": "Temperature \u0026 Pressure Measurement",
  "Id": "0x0102",
  "Channels": [
    {
      "Data": [
        {
          "Channel0": [
            {
              "Enable": 0,
              "Unit": "Celsius"
            }
          ],
          "Channel1": [
            {
              "Enable": 0,
              "Unit": "Celsius"
            }
          ],
          "Channel2": [
            {
              "Enable": 0,
              "Unit": "Celsius"
            }
          ]
        }
      ]
    }
  ],
  "Events": [
    {
      "event1": 0,
      "event2": 0
    }
  ],
  "Diagnostics": [
    {
      "diag1": 0,
      "diag2": 0
    }
  ],
  "Functions": [
    {
      "Function-1": [
        {
          "Function": "2d"
        }
      ]
    }
  ]
}
""")

json2 = json.loads("""
{
  "Name": "Temperature \u0026 Pressure Measurement",
  "Id": "0x0102",
  "Channels": [
    {
      "Data": [
        {
          "Channel0": [
            {
              "Enable": 0,
              "Unit": "Celsius"
            }
          ],
          "Channel1": [
            {
              "Enable": 0,
              "Unit": "Celsius"
            }
          ],
          "Channel2": [
            {
              "Enable": 0,
              "Unit": "Celsius"
            }
          ]
        }
      ]
    }
  ],
  "Events": [
    {
      "event1": 0,
      "event2": 0
    }
  ],
  "Diagnostics": [
    {
      "diag1": 0,
      "diag2": 0
    }
  ],
  "Functions": [
    {
      "Function-1": [
        {
          "Function": "dd",
          "Function2":"d3"
        }
      ]
    }
  ]
}
""")


# This gives the difference between the json and this is what we want to operate on ! the 'res' may vary based on the changes made to json2 


res = str(diff(json1, json2))


print('----------------------')
print('-------  DIFF  -------')
print('----------------------')
print(f'{res}')
print('----------------------')
print('----------------------')
print('')
print('----------------------')
print('---Expected Output---')
print('----------------------')
print('{"Functions":[{"Function-1":[{"Function":"dd","Function2":"d3"}]}]}')
print('----------------------')
print('----------------------') 

EDIT::

To be more clear the res variable will change always. So i think it cannot always be achieved by using string replace because number of bracket may change based on the difference from json1 and json2

CodePudding user response:

A specific answer would be using the string.replace() method, combined with the json package:

import re
import json
from pprint import pprint

x = {'Functions': {0: {'Function-1': {0: {'Function': 'dd', 'Function2': 'd3'}}}}}

tmp1 = json.dumps(x)
tmp2 = re.sub(' {"[0-9]": {','[{',tmp1).replace('}}}}}','}]}]}')
mydict = json.loads(tmp2)

pprint(mydict)
#{'Functions': [{'Function-1': [{'Function': 'dd', 'Function2': 'd3'}]}]}

CodePudding user response:

Here, basic idea is to convert nested dictionary to flat and after removing 0 again convert from flat to dict using ndicts.

Code:

from ndicts.ndicts import NestedDict

fd = list(pd.json_normalize(Mydict).T.to_dict().values())[0]

nd = NestedDict()
for key, value in fd.items():
    n_key = tuple(key.split(".0."))
    nd[n_key] = value
    
nd

Output:

NestedDict({'Functions': {'Function-1': {'Function': 'dd', 'Function2': 'd3'}}})

Package ref

Kudos

  • Related