将JSON值另存为另一个JSON文件

时间:2016-08-24 14:01:35

标签: javascript json

我有一个类似下面的JSON文件:

{
  "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
    }
  }]
}

我想将Polygon键的值提取到另一个JSON对象,如下所示

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

现在我使用

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

其中polgonJson包含我的初始JSON文件,我得到一个额外的[]括号,这不允许我创建一个正确的JSON文件,如下所示。

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

如何摆脱那些[]括号或正确提取值?

1 个答案:

答案 0 :(得分:1)

当您对JSON对象进行字符串化时,它会添加额外的[]括号,因为它将您的对象作为数组。要从text变量中提取JSON,您需要获取该数组中第一个(也是唯一的)元素的值。

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