Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove JSON root

I have the following string on a JavaScript variable:

my_Variable = "{"Domini":[{"cod_domini":"1","nom_domini":"Sant Esteve de Palautordera"},{"cod_domini":"2","nom_domini":"Parc Natural del Montseny"},{"cod_domini":"5","nom_domini":"Sant Pere de Vilamajor"},{"cod_domini":"6","nom_domini":"Santa Maria i Mosqueroles"}]}"

I need to remove the root at the top of string Domini so the resultant string looks like this:

my_Variable = [{"cod_domini":"1","nom_domini":"Sant Esteve de Palautordera"},{"cod_domini":"2","nom_domini":"Parc Natural del Montseny"},{"cod_domini":"5","nom_domini":"Sant Pere de Vilamajor"},{"cod_domini":"6","nom_domini":"Santa Maria i Mosqueroles"}]

I've tried to parse JSON to an object using JSON.parse() function and it works, but then I don't know how to retrieve the data and handle it to generate a new JSON without root.

Should I be using some kind of loop?

like image 446
Calypo Gunn Avatar asked Dec 15 '22 16:12

Calypo Gunn


1 Answers

It's simple:

my_Variable = my_Variable.Domini;

After JSON parse.

So code will be like:

my_Variable = "{"Domini":[{"cod_domini":"1","nom_domini":"Sant Esteve de Palautordera"},{"cod_domini":"2","nom_domini":"Parc Natural del Montseny"},{"cod_domini":"5","nom_domini":"Sant Pere de Vilamajor"},{"cod_domini":"6","nom_domini":"Santa Maria i Mosqueroles"}]}";
my_Variable = JSON.parse( my_Variable );
my_Variable = my_Variable.Domini;
console.log( my_Variable ); // [{"cod_domini":"1","nom_domini": ...
like image 199
antyrat Avatar answered Dec 30 '22 19:12

antyrat