Is there a way to remove a parent layer from a JSON object? For example, let's say I have the following JSON object:
{
"Hello": "World",
"Parent": {
"key1": "val1",
"key2": "val2",
"key3": {
"key3a": "val3a",
"key3b": "val3b"
},
"key4": "val4"
}
}
But I want to remove the Parent
layer and have the JSON object read like the following:
{
"Hello": "World",
"key1": "val1",
"key2": "val2",
"key3": {
"key3a": "val3a",
"key3b": "val3b"
},
"key4": "val4"
}
Is there a way to do this?
I would preferably like to accomplish this using Python, but if anyone knows of a way I am open to using other methods to get this done.
To remove JSON element, use the delete keyword in JavaScript.
The dump() method is used when the Python objects have to be stored in a file. The dumps() is used when the objects are required to be in string format and is used for parsing, printing, etc, . The dump() needs the json file name in which the output has to be stored as an argument.
json. dump() method used to write Python serialized object as JSON formatted data into a file. json. dumps() method is used to encodes any Python object into JSON formatted String.
Can be done quite easily with dict.pop
and dict.update
:
import json
data = {
"Hello": "World",
"Parent": {
"key1": "val1",
"key2": "val2",
"key3": {
"key3a": "val3a",
"key3b": "val3b"
},
"key4": "val4"
}
}
data.update(data.pop("Parent"))
print(json.dumps(data, indent=4))
Output:
{ "Hello": "World", "key1": "val1", "key2": "val2", "key3": { "key3a": "val3a", "key3b": "val3b" }, "key4": "val4" }
This also has the advantage that this will work for pretty much any version of Python.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With