Home > Blockchain >  How to read the dynamic objects data present in JSON?
How to read the dynamic objects data present in JSON?

Time:05-04

I am obtaining a JSON from another application. I would like to parse that JSON and read the data present in them. The JSON contains some of the user-defined data which are dynamic and the key/value pair can be dynamic so I am a bit confused about how to read these dynamic data and do further processing.

Following is the sample JSON that I would like to process:

{
  "context": [
    {
      "one": "https://example.one.com"
    },
    {
      "two": "https://example.two.com"
    },
    {
      "three": "https://example.three.com"
    }
  ],
  "name": "Batman",
  "age": "30",
  "one:myField": {
    "two:myField2": "Hello"
  },
  "three:myField3": "Hello2"
}

I am able to read some of the static/well-defined data directly such as name & age but I am not understanding how to read some of the user-defined/dynamic data from this JSON as it does not have a definite key/value or there is no guarantee that it will appear in the order after the age property.

I am trying to find a way to read/obtain all the user-defined data from this JSON:

  "one:myField": {
    "two:myField2": "Hello"
  },
  "three:myField3": "Hello2"

Is there a direct way to achieve this or use some library? I am developing the application using Vuejs/Nuxtjs.

CodePudding user response:

I think that's not the best api you are using, you should have constant object parameters that you always know how to find things. If you want to find not known parameters you can parse JSON to object and loop throug it.

const object = { a: 1, b: 2, c: 3 };

for (const property in object) {
  console.log(`${property}: ${object[property]}`);
}

CodePudding user response:

You can simply achieve that by iterating over Object.keys().

Demo :

const jsonData = {
  "context": [
    {
      "one": "https://example.one.com"
    },
    {
      "two": "https://example.two.com"
    },
    {
      "three": "https://example.three.com"
    }
  ],
  "name": "Batman",
  "age": "30",
  "one:myField": {
    "two:myField2": "Hello"
  },
  "three:myField3": "Hello2"
};

Object.keys(jsonData).forEach(key => {
    if (typeof jsonData[key] === 'object') {
    Object.keys(jsonData[key]).forEach(innerObjKey => {
        console.log(innerObjKey, jsonData[key][innerObjKey])
    })
  } else {
     console.log(key, jsonData[key])
  }
})

  • Related