TransWikia.com

Split JSON to multiple Objects

Stack Overflow Asked by Marcio Lino on December 11, 2021

I have a JSON file like this:

{
"qtd_if": {"agreg": "First", "name": "IFs"},
"rnk_pib_tot": {"agreg": "Count","name": "PIB Tot"},
"rnk_pib_uf": {"agreg": "Sum", "name": "PIB UF"}
}

How can I have three Objects from the above JSON, being:

1st. Object
agr = {qtd_if : "First", rnk_pib_tot: "Count", rnk_pib_uf: "Sum"}

2st. Object
col = {0: qtd_if, 1: rnk_pib_tot, 2: rnk_pib_uf}

3st. Object
lab = {0: IFs, 1: PIB Tot, 2: PIB UF}

2 Answers

How about this one:

// First convert your JSON to object with JSON.parse(),
// I use the object directly for brevity.
const sourceObject = {
    qtd_if: { agreg: "First", name: "IFs" },
    rnk_pib_tot: { agreg: "Count", name: "PIB Tot" },
    rnk_pib_uf: { agreg: "Sum", name: "PIB UF" },
};

const sourceObjectKeys = Object.keys(source);

const agr = {};
const col = {};
const lab = {};

sourceObjectKeys.forEach((key, i) => {
    agr[key] = sourceObject[key]['agreg'];
    col[i.toString()] = key;
    lab[i.toString()] = sourceObject[key]['name'];
});

Answered by amedina on December 11, 2021

First you deserialize the JSON, then you create variables referencing the parts you want to use.

var obj = JSON.parse('{"qtd_if": {"agreg": "First", "name": "IFs"},"rnk_pib_tot": {"agreg": "Count","name": "PIB Tot"},"rnk_pib_uf": {"agreg": "Sum", "name": "PIB UF"}}');

var agr = obj.qtd_if;
var col = obj.rnk_pib_tot;
var lab = obj.rnk_pib_uf;

Answered by casenonsensitive on December 11, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP