Search code examples
c#json.net

How to remove parent element from json in c#


How to covert the below json

{"data":{"id":12,"name":"jeremy","email":"[email protected]"}}

to

{"id":12,"name":"jeremy","email":"[email protected]"}

I want to remove the "data" element from json.


Solution

  • With json.net it's fairly straightforward

    var input = "{\"data\":{\"id\":12,\"name\":\"jeremy\",\"email\":\"[email protected]\"}}";
    var result = JObject.Parse(input)["data"].ToString(Formatting.None);
    Console.WriteLine(result);
    

    Note : Formatting.None is only to preserve the formatting you had in your original example

    Or Text.Json

    var result = JsonDocument.Parse(input).RootElement.GetProperty("data").ToString();
    

    Output

    {"id":12,"name":"jeremy","email":"[email protected]"}
    

    Additional Resources

    JObject.Parse Method (String)

    Load a JObject from a string that contains JSON.

    JObject.Item Property (String)

    Gets or sets the JToken with the specified property name.

    JToken.ToString Method (Formatting,JsonConverter[])

    Returns the JSON for this token using the given formatting and converters.

    Formatting Enumeration

    None 0 No special formatting is applied.


    Text.Json

    JsonDocument.Parse Method

    Provides a mechanism for examining the structural content of a JSON value without automatically instantiating data values.

    JsonDocument.RootElement Property

    Gets the root element of this JSON document

    JsonElement.GetProperty Method

    Gets a JsonElement representing the value of a required property identified by propertyName.