0

I have a JSON that contains a lot of data, here's an example of it:

{
   "type":"doc",
   "content":[
      {
         "type":"paragraph",
         "content":[
            {
               "text":"this is a simple page, about a simple umbrella.",
               "type":"text"
            }
         ]
      },
      {
         "type":"paragraph",
         "content":[
            {
               "text":"you can use this text to find the umbrella page.",
               "type":"text"
            }
         ]
      },
      {
         "type":"paragraph",
         "content":[
            {
               "text":"do you like it?",
               "type":"text"
            }
         ]
      }
}

I want to extract the value of text key, no matter where the key is located. I'm trying to go over the keys using Object.keys but it only returns the top-level keys:

for (let x of Object.keys(someJson)) {
    console.log(x);
}

How can I find all the values of text in this JSON, no matter where in the JSON it is?

1
  • you need to use recursion Commented Oct 27, 2021 at 8:33

2 Answers 2

1

You can use JSON.stringify trick, you can intercept all keys from it

function find(obj: object, key: string) {
  const ret: any[] = [];
  JSON.stringify(obj, (_, nested) => {
    if (nested && nested[key]) {
      ret.push(nested[key]);
    }
    return nested;
  });
  return ret;
};

...

const o = {
  key: '123',
  a: {
    key: 'hello',
    b: [
      {
        c: {
          key: 123,
        },
      },
    ],
  },
};
it('123', () => {
  console.log(JSON.stringify(find(o, 'key'))); // ["123","hello",123]
});
Sign up to request clarification or add additional context in comments.

Comments

0

if you want for generic JSON just call this function and pass your object :

function printText(obj){
    if(Array.isArray(obj)){
        for(const o of obj){
            printText(o);
        }
    }else if(typeof obj === "object"){
        if (obj){
            for(const o of Object.keys(obj)){
                 if(o==="text"){
                      console.log(obj.text);
                 }else{
                      printText(obj[o]);
                 }
            }
        }
    }

}

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.