2

I want to delete any JSON element by using their key. For example,

This is my JSON data:

{
  "CreateprivateNetwork": {
    "description": "Creatinganetwork.",
    "input": {
        "body": {
            "network": {
                "name": "$.networkname",
                "admin_state_up": "sdfdsf"
            }
        }
    },
    "action": "neutron.create_network",
    "publish": {}
  }
}

I want to delete the element "name" from this JSON

PATH TO DELETE : "CreateprivateNetwork.input.body.network.name".

Please help me to solve this problem.

Note: This path may change Dynamically. So I have to delete any elements from dynamic JSON.

1 Answer 1

4

Use JSON.parse to remove keys that you don't need

function format(json_string, key_to_skip) {
    return JSON.parse(json_string, function (key, value) {
        if (key !== key_to_skip) {
            return value;
        }
    });    
}

var json = {
    "CreateprivateNetwork": {
        "description": "Creatinganetwork.",
        "input": {
            "body": {
                "network": {
                    "name": "$.networkname",
                    "admin_state_up": "sdfdsf"
                }
            }
        },
        "action": "neutron.create_network",
        "publish": {}
    }
};

alert(JSON.stringify(format(JSON.stringify(json), 'name')));

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

3 Comments

Thank you so much its working fine.... But it removes only the key value ...For example , key_to_skip = 'name' means i want to delete the "name" and its value "$.networkname".
"key_to_skip" will automatically remove it's value too. A "key" should be present to hold it's "value" right ? :)
Ya thank you....I slightly modify your code...Now everything is properly working ....Thank you so much

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.