Issue
{'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
Solution
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'}]}]}
Answered By - R. Baraiya
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.