Skip to content Skip to sidebar Skip to footer

How To Get The Value By A Key From A Super Nested Json

'_embedded': { 'cscaia:status_report': { '_links': { 'self': { 'title': 'status_report', 'name': 'status_report', 'href': 'https://api.dxc-dev-aia.hub-1.dev

Solution 1:

You could take a recursive approach and return if a value is found.

functiongetValue(object, key) {
    var value;

    if (!object || typeof object !== 'object') return;
    if (key in object) return object[key];

    Object.values(object).some(v => {
        value = getValue(v, key)
        return value !== undefined;
    });    

    return value;
}

var data = { _embedded: { "cscaia:status_report": { _links: { self: { title: "status_report", name: "status_report", href: "https://api.dxc-dev-aia.hub-1.dev.us.insurance.dxc.com/quotes/ID-mrMxY1Dg/status_report" }, type: { href: "https://diaas-dev.gtaia-test-domain.net/std-dev-lux-13100/insurance/schemas/quotes/statusReportDocument" }, up: { href: "https://api.dxc-dev-aia.hub-1.dev.us.insurance.dxc.com/quotes/ID-mrMxY1Dg" } }, consistent: false, messages: [{ message: "Incomplete attribute", context: [{ propertyNames: ["quote$distributor_id"] }], severity: "error", code: "incomplete_attr" }] } } };

console.log(getValue(data, 'severity'));
console.log(getValue(data, 'href'));

Solution 2:

Just use a recursive function to run through all level.

var _embedded = {
  "cscaia:status_report": {
    "_links": {
      "self": {
        "title": "status_report",
        "name": "status_report",
        "href": "https://api.dxc-dev-aia.hub-1.dev.us.insurance.dxc.com/quotes/ID-mrMxY1Dg/status_report"
      },
      "type": {
        "href": "https://diaas-dev.gtaia-test-domain.net/std-dev-lux-13100/insurance/schemas/quotes/statusReportDocument"
      },
      "up": {
        "href": "https://api.dxc-dev-aia.hub-1.dev.us.insurance.dxc.com/quotes/ID-mrMxY1Dg"
      }
    },
    "consistent": false,
    "messages": [
      {
        "message": "Incomplete attribute",
        "context": [
          {
            "propertyNames": [
              "quote$distributor_id"
            ]
          }
        ],
        "severity": "error",
        "code": "incomplete_attr"
      }
    ]
  }
}

functionrecursive_search (object) {

  let output = null;

  //check if object is an array or objectif (Array.isArray (object)) {
  
    //check every array-element recursivefor (let i in object)
      output = recursive_search (object[i])

  } elseif (typeof object === 'object') {
  
    //get all keys of objectlet keys = Object.keys (object);
    
    //check every key if it is 'serverity'. if not check every property recursive for (let i in keys)
      if (keys[i] === 'severity') {
      
        output = object[keys[i]];
        break;
      
      } elseif (typeof object === 'object')
        output = recursive_search (object[keys[i]])
  
  }
  
  return output;

}

//get serverity
serverity = recursive_search (_embedded)

console.log ('serverity = ' + serverity);

Solution 3:

Assuming you want to achieve this using C# you could try querying all descendends using Newtonsoft.Json.Linq untill you find the right Property.

This should work (demo):

publicstatic T GetJsonPropertyValue<T>(string json, string property)
{
    var parsedJson = JObject.Parse(json);
    var token = parsedJson.Descendants()
        .FirstOrDefault(t => t.Type == JTokenType.Property
            && ((JProperty)t).Name == property);
    return token is JProperty
        ? token.First().Value<T>()
        : token.Value<T>();
}

From your example:

staticvoidMain(string[] args)
{
    var json = @"{
     ""_embedded"": {
        ""cscaia:status_report"": {
            ""_links"": {
                ""self"": {
                    ""title"": ""status_report"",
                    ""name"": ""status_report"",
                    ""href"": ""https://api.dxc-dev-aia.hub-1.dev.us.insurance.dxc.com/quotes/ID-mrMxY1Dg/status_report""
                },
                ""type"": {
                    ""href"": ""https://diaas-dev.gtaia-test-domain.net/std-dev-lux-13100/insurance/schemas/quotes/statusReportDocument""
                },
                ""up"": {
                    ""href"": ""https://api.dxc-dev-aia.hub-1.dev.us.insurance.dxc.com/quotes/ID-mrMxY1Dg""
                }
            },
            ""consistent"": false,
            ""messages"": [
                {
                    ""message"": ""Incomplete attribute"",
                    ""context"": [
                        {
                            ""propertyNames"": [
                                ""quote$distributor_id""
                            ]
                        }
                    ],
                    ""severity"": ""error"",
                    ""code"": ""incomplete_attr""
                }
            ]
        }
    }
}";
    var context = GetJsonPropertyValue<dynamic>(json, "context");
    var severity = GetJsonPropertyValue<string>(json, "severity");
    Console.WriteLine(severity);
    Console.WriteLine(context);
    Console.ReadKey();
}

Post a Comment for "How To Get The Value By A Key From A Super Nested Json"