How to remove the first key that surrounds all the values of a JSON

0

Is it possible to remove the first key { } from 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);
    
asked by anonymous 14.10.2017 / 02:41

1 answer

1

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

For formatting you can either:

  • Call the Stringify with a specific spacing
  • Cut the first and last caratere with slice(1,-1)
  • Use the <pre> tag 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 Strings interpolation could construct the html as follows :

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

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

    
14.10.2017 / 03:03