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

2 Answers 2

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

Sign up to request clarification or add additional context in comments.

3 Comments

hi thanks for your effort. but it seems like the Square brackets are missing from the output.
Please refer an updated code.Thanks
good approach here , please add some explanation to make it more readable and understandable.
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'}]}]}

2 Comments

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

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.