0

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

var 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?

2
  • @str. It is wrong. Variable text is of type string, so text[0] === '['. Commented Aug 24, 2016 at 15:28
  • True, it should be newPolygonJSON[0]. Commented Aug 24, 2016 at 15:57

1 Answer 1

1

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]);
Sign up to request clarification or add additional context in comments.

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.