Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a way to remove a layer from a JSON object?

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.

like image 337
mattc-7 Avatar asked Nov 01 '19 14:11

mattc-7


People also ask

How do you remove an element from a JSON object?

To remove JSON element, use the delete keyword in JavaScript.

What is JSON dumps () method?

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.

What is JSON dump and dumps?

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.


1 Answers

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.

like image 197
ruohola Avatar answered Sep 22 '22 00:09

ruohola