3
{'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

DeLorean
  • 186
  • 13

2 Answers2

2

Code:

from ndicts.ndicts import NestedDict

STEP 1// Convert nested dict to flat dict

fd = list(pd.json_normalize(Mydict).T.to_dict().values())[0] 
#Output {'Functions.0.Function-1.0.Function': 'dd', 'Functions.0.Function-1.0.Function2': 'd3'}

STEP 2// Convert flat dictionary to nested by split/removing the 0

nd = NestedDict()
for key, value in fd.items():
    n_key = tuple(key.split(".0."))
    nd[n_key] = value
    
dic = nd.to_dict()
dic
 
#Output
{'Functions': {'Function-1': {'Function': 'dd', 'Function2': 'd3'}}}

STEP 3// To add [], you can convert to dict to json and replace { with [{.

json.loads(json.dumps(dic).replace('{','[{').replace('}','}]'))[0]

Desire Outout

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

Package ref

question ref

R. Baraiya
  • 1,490
  • 1
  • 4
  • 17
1

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'}]}]}
willwrighteng
  • 1,411
  • 11
  • 25
  • thanks for the reply, this wouldn't work in my case as number of '{0:' might vary. and also the position of the ']' will not always be same. – DeLorean Oct 13 '22 at 08:23
  • 1
    @DeLorean switch out the first replace() with re.sub() -- I'll take a look at the pattern for the closing square bracket, probably another re.sub() ([relevant SO post](https://stackoverflow.com/questions/46090928/python-regex-replace-numbers-and-special-characters-except-years)) – willwrighteng Oct 13 '22 at 08:54