1

I have the following object. How to turn this object into a Json?

 initializeItems() {
   this.items = [
 {id: '1', nome:'Abaéte', rua:'Moacir', cidade:'Capão da Canoa', bairro:'Centro', numero:'396', ano:'1964', aptos:'55', adm:'Adsel', zelador:'Hugo', contato1:'(51) 0 0000 - 0000', contato2: '(51) 0000 - 0000', imagem:'assets/img/Abaete-min.jpg'},
];

And I want to turn it into Json

{
"predios" : {
    "adm" : "Adsel",
    "ano" : 1964,
    "aptos" : 55,
    "bairro" : "Centro",
    "cidade" : "Capão da Canoa",
    "contato1" : "(51) 9 0000 - 0000",
    "contato2" : "(51) 0000 - 0000",
    "id" : 1,
    "imagem" : "Abaete-min.JPG",
    "nome" : "Abaéte",
    "numero" : 396,
    "rua" : "Moacir",
    "zelador" : "Hugo"
  }
}

2 Answers 2

4

you can use

JSON.stringify()

function initialize() {
var items = [{id: '1', nome:'Abaéte', rua:'Moacir', cidade:'Capão da Canoa', bairro:'Centro', numero:'396', ano:'1964', aptos:'55', adm:'Adsel', zelador:'Hugo', contato1:'(51) 0 0000 - 0000', contato2: '(51) 0000 - 0000', imagem:'assets/img/Abaete-min.jpg'}];

var jsonObject = {"predios": items[0]}

console.log(JSON.stringify(jsonObject));
} 
initialize();

Sign up to request clarification or add additional context in comments.

Comments

1

To achieve that,

  1. Get the first element of this.items as it is an array

  2. Assign the first element within an object

var prediosJsonObj = {"predios": this.items[0]}


To clear up any confusion, JSON supports 2 types of data structure:

  • Collection of name/value pairs (Object, dictionary, etc)

  • Ordered list of values (Array, list, etc)

this.items is already considered JSON with an array structure. What you wanted is how to transform JSON array to a JSON object.

https://www.w3resource.com/JSON/structures.php

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.