Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

230
Views
Actualizar valor específico en archivo JSON

Estoy buscando una manera de encontrar un valor json específico por su nombre y establecer su valor en nulo. La construcción del archivo json puede ser cualquier cosa, no siempre es la misma.

Digamos que el json se ve así:

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

El resultado que busco es este:

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

Cuando el objeto es más complicado, también debería funcionar.

 { "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": "" } }]}

Intenté usar clases JArray, JObject, etc., pero solo funciona si la propiedad ["correo electrónico"] es el primer hijo, no más profundo. No estoy seguro de cómo lograr esto.

 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 answers
Answer question

0

Usando NewtonSoft, una vez hice una función de aplanamiento para analizar archivos json de cualquier profundidad:

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

Devuelve una lista plana de todas las JsonProperty de "punto final" en un archivo (digamos: todas las "xyx" : primitive value ). Usándolo, simplemente puede deserializar su Json, encontrar todas las propiedades de "correo electrónico" y establecer su valor en 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();

Resultado para el json "más complicado" (con un correo electrónico más profundo agregado para hacerlo más divertido):

 { "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 Report

0

Con System.Text.Json y Utf8JsonWriter puede procesar y escribir su JSON de forma recursiva:

 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); } }

Uso:

 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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!