How to remove the first key that involves all values from a JSON

Asked

Viewed 211 times

0

It is possible to remove the first key { } of a JSON and add in lines below (Enter), of each value?

var obj = {
  "arvore": "/",
  "avo": "obadias",
  "pai": {
    "eu": "Leonardo"
  }
}

class Access {
  static getRaiz(obj) {
    return JSON.stringify(obj);
  }
}

document.body.innerHTML = Access.getRaiz(obj);

1 answer

1


If I understand correctly, you are trying to visually format the object that came out of a JSON.

For the formatting you want you can:

  • Call the Stringify with a specific spacing
  • Cut the first and last character with slice(1,-1)
  • Use the label <pre> to keep formatting in html

Example:

var obj = {
  "arvore": "/",
  "avo": "obadias",
  "pai": {
    "eu": "Leonardo"
  }
}

class Access {
  static getRaiz(obj) {
    //4 é o numero de espaços que cada objeto anda para dentro
    return JSON.stringify(obj, undefined, 4); 
  }
}

//aqui utiliza o <pre> no inicio e o slice para cortar primeiro e ultimo
document.body.innerHTML = '<pre>' + Access.getRaiz(obj).slice(1,-1) + '</pre>';

With string interpolation could build html as follows:

document.body.innerHTML = `<pre>${Access.getRaiz(obj).slice(1,-1)}</pre>`;

This second way ends up simplifying a lot when you have to include many expressions in a String.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.