Hiranava Das Hiranava Das - 3 months ago 8
JSON Question

Save JSON value as another JSON file

I have a JSON file like below:

{
"soils": [{
"mukey": "658854",
"mukeyName": "Meggett-Kenansville-Garcon-Eunola-Blanton-Bigbee (s1517)",
"sl_source": "Fl soil map",
"cokey": "3035468",
"soilName": "Eunola",
"comppct_r": 20,
"compArea": "9.96",
}],
"asfirs": [{
"long": -82.96896600817682,
"lat": 29.977675992923395
}],
"polygon": [{
"rings": [[[-9235836.910744485,
3501136.0564117758],
[-9235798.692230342,
3500237.921329426],
[-9236553.507884657,
3500667.87961353],
[-9235836.910744485,
3501136.0564117758]]],
"spatialReference": {
"wkid": 102100,
"latestWkid": 3857
}
}]
}


I want extract the value of Polygon key to another JSON object like below

{
"rings": [[[-9161396.799823288,
3453315.140590871],
[-9160708.866568722,
3453095.3841345515],
[-9161349.02668061,
3452751.4175072685],
[-9161396.799823288,
3453315.140590871]]],
"spatialReference": {
"wkid": 102100,
"latestWkid": 3857
}
}


Now when I do it using

key3 = "polygon"
var newPolygonJSON = polygonJson[key3];
var text = JSON.stringify(newPolygonJSON);


where
polgonJson
contains my initial JSON file I get an extra
[]
bracket which is not allowing me to create a proper JSON file, like below.

[{
"rings": [[[-9235836.910744485,
3501136.0564117758],
[-9235798.692230342,
3500237.921329426],
[-9236553.507884657,
3500667.87961353],
[-9235836.910744485,
3501136.0564117758]]],
"spatialReference": {
"wkid": 102100,
"latestWkid": 3857
}
}]


How can I get rid of those
[]
brackets or extract the value properly?

Answer

When you stringify JSON object, it puts extra [] brackets because it takes your object as an array. To extract JSON from text variable, you need to get value of the first (and only) element in that array.

var key3 = 'polygon';
var newPolygonJSON = polygonJson[key3];
var text = JSON.stringify(newPolygonJSON)[0];

Or you can extract it before stringifying.

var key3 = 'polygon';
var newPolygonJSON = polygonJson[key3];
var text = JSON.stringify(newPolygonJSON[0]);