Remove JSON Root

I have the following line in 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 the Domini string so that the resulting 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 tried JSON.parse() JSON into an object using the JSON.parse() function, and it works, but then I don’t know how to extract the data and process it to create a new JSON without root.

Should I use some kind of loop?

+4
source share
4 answers

It's simple:

 my_Variable = my_Variable.Domini; 

After parsing JSON.

So, the code will look like this:

 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": ... 
+6
source
 var obj = JSON.parse(json); obj = [Object.keys(obj)[0]]; var newJson = JSON.stringify(obj); 

or by avoiding ES5 features like Object.keys:

 var obj = JSON.parse(json); for (var key in obj) { if (!Object.prototype.hasOwnProperty.call(obj, key)) continue; obj = obj[key]; break; } var newJson = JSON.stringify(obj); 
+3
source

Given that you want to return to the line after deleting the key.

 my_Variable = JSON.stringify(JSON.parse(my_Variable).Domini); 

Structure

 JSON.parse(my_Variable) 

Parses a string into a JSON object.

 JSON.parse(my_Variable).Domini 

Gets the value of the Domini property.

 JSON.stringify(JSON.parse(my_Variable).Domini) 

Encodes it back to a string.

+2
source

If you want your variable to go through, do the following (you mentioned that you already did this, but I added it for completeness)

 var parsedJson = JSON.parse(my_Variable); 

when you disassemble it, follow these steps:

 var JsonWithoutDominiAsRoot = parsedJson.Domini; 

You can "." your path through the various attributes of your new json object. Domini was just one of them.

+1
source

All Articles