Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

232
Visualizações
Update specific value in JSON file

I'm looking for a way to find a specific json value by its name and set its value to null. The construction of the json file can be anything, it's not always the same.

Let's say the json looks like this:

[
{
    "id": "1111",
    "email": "email@email.com",
},
{
    "id": "2222",
    "email": "email2@email2.com",
}]

The result I'm looking for is this:

[
{
    "id": "1111",
    "email": null,
},
{
    "id": "2222",
    "email": null,
}]

When the object is more complicated it should work too.

{
"reservations": [
    {
        "id": "111",
        "bookingId": "",
        "status": "",
        "checkInTime": "",
        "checkOutTime": "",
        "property": {
            "id": "",
            "code": "",
            "name": "",
        },
        "primaryGuest": {
            "firstName": "",
            "middleInitial": "",
            "lastName": "",
            "email": "email@email.com",
            "phone": "",
            "address": {
                "addressLine1": "",
                "postalCode": "",
                "city": "",
                "countryCode": ""
            }
        },
        "booker": {
            "firstName": "",
            "middleInitial": "",
            "lastName": "",
            "email": "email2@email.com",
            "phone": ""
        }
   }]}

I've tried to use JArray, JObject classes etc, but it only works if the propety["email"] is the first child, not deeper. Not sure how to accomplish this.

 private JObject HashSensitiveData(JContainer jContainer)
    {
        if (!jContainer.Descendants().Any())
        {
            return null;
        }

        var objects = jContainer.Descendants().OfType<JObject>();

        foreach (var property in objects)
        {
            foreach (var emailProperty in property.Properties().Where(x => x.Name.CaseInsensitiveContains(LoggerHashedProperties.Email.ToString())))
            {
                var email = emailProperty.Value.ToString();
                property[emailProperty.Name] =null
            }
        }

        return HashSensitiveData(jContainer);
    }
over 4 years ago · Santiago Trujillo
2 Respostas
Responde à pergunta

0

Using NewtonSoft, I once made a flatten function to analyse json files of any depth:

IEnumerable<JProperty> Flatten(JToken token)
{
    return token.Children<JProperty>().Concat(
        token.Children().SelectMany(t => Flatten(t)))
        .Where(t => t.Value is JValue);
}

It returns a flat listing of all "endpoint" JsonPropertys in a file (say: all "xyx" : primitive value entries). Using it you can simply deserialize your Json, find all "email" properties and set their value to null:

var jobj = JsonConvert.DeserializeObject<JObject>(getJson());

var flattened = Flatten(jobj);

foreach (var jprop in flattened.Where(t => t.Name == "email"))
{
    jprop.Value = null;
}
var json = JsonConvert.SerializeObject(jobj).Dump();

Result for the "more complicated" json (with one deeper email added to make it more fun):

{
  "reservations": [
    {
      "id": "111",
      "bookingId": "",
      "status": "",
      "checkInTime": "",
      "checkOutTime": "",
      "property": {
        "id": "",
        "code": "",
        "name": ""
      },
      "primaryGuest": {
        "firstName": "",
        "middleInitial": "",
        "lastName": "",
        "email": null,
        "phone": "",
        "address": {
          "email": null,
          "addressLine1": "",
          "postalCode": "",
          "city": "",
          "countryCode": ""
        }
      },
      "booker": {
        "firstName": "",
        "middleInitial": "",
        "lastName": "",
        "email": null,
        "phone": ""
      }
    }
  ]
}
over 4 years ago · Santiago Trujillo Relatório

0

With System.Text.Json and Utf8JsonWriter you can process and write your JSON recursively:

public static void RemoveContent(JsonElement element, Utf8JsonWriter writer)
{
    // Current element is an array, so we have to iterate over all elements.
    if (element.ValueKind == JsonValueKind.Array)
    {
        writer.WriteStartArray();
        foreach (var e in element.EnumerateArray())
        {
            RemoveContent(e, writer);
        }
        writer.WriteEndArray();
    }
    // Current element is an object, so we have to process all properties.
    else if (element.ValueKind == JsonValueKind.Object)
    {
        writer.WriteStartObject();
        foreach (var e in element.EnumerateObject())
        {
            writer.WritePropertyName(e.Name);

            // * Process specific elements. ************************************************
            if (e.Name == "email") { writer.WriteNullValue(); }
            else RemoveContent(e.Value, writer);
        }
        writer.WriteEndObject();
    }
    // We are at the leaf (a string property, ...) and we write this as it is.
    else
    {
        element.WriteTo(writer);
    }
}

Usage:

using var stream = new MemoryStream();
// We have to flush writer before reading it's content.
using (var writer = new Utf8JsonWriter(stream, new JsonWriterOptions { SkipValidation = true }))
{
    var element = JsonDocument.Parse(jsonStr).RootElement;
    RemoveContent(element, writer);
}
// Stream contains a byte array with UTF-8 content.
// If you want a string, you can use UTF8 decoding.
var json = System.Text.Encoding.UTF8.GetString(stream.ToArray());
Console.WriteLine(json);
over 4 years ago · Santiago Trujillo Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda