我如何替换默认JSON.用我自己的变量将变量K和A字符串化

How can i replace default JSON.stringify variable K and A with my own variable

本文关键字:变量 自己的 字符串 我自己 何替换 替换 JSON 默认      更新时间:2023-09-26

我想通过ajax将我的多边形点放入数据库。所以我像这样使用

function StorePolygon(id, poly_points) {
   var html;
   // The values of id=1001 and poly_points=((47.53208121578362, 7.705052197034092),
   //   (47.53188401121172, 7.704971730763646),(47.53189169452062, 7.705076336915226))
   $.ajax({
     url: url_prefix + "SetPolygonInfo",
     data: ({
        'id': id,
        'polypoints': JSON.stringify(poly_points),
        'as_json': 1
    }),
    async: false,
    dataType: "json",
    success: function(result) {
        html = result.html;
     },
     error: function(data, status, e) {
        alert(e);
     }
 });
 return html;
 }

JSON.stringify(poly_points)产生如下

[{"k":47.53208121578362,"A":7.705052197034092},
 {"k":47.53188401121172,"A":7.704971730763646}, 
 {"k":47.53189169452062,"A":7.705076336915226}]

我想用我自己的变量代替K和a,有人能帮助吗?

您可以使用map来创建一个新的对象数组,其中包含您想要使用的键和JSON。将数组改为字符串化:

JSON.stringify( poly_points.map(function (point){
  return {
    custom_key_for_k : point.k,
    custum_key_for_A : point.A
  };
}) )

您需要加载map以支持9版本之前的Internet Explorer,或者使用任何包含它的Javascript库中的等效函数

我只是不想依赖JSON.stringify(poly_points)变量存储在DB中。所以我这样做了

function StorePolygon(id, poly_points) {
var html;
var olist = []
var obj = {}
/*
JSON.stringify(poly_points.map(function(point) {
    obj = {
        'x': point.k,
        'y': point.B
    }
    olist.push(obj)
}))*/
for(var i=0;i<poly_points.length;i++){
var xy = poly_points[i];
obj = {
        'x': xy.lat(),
        'y': xy.lng()
    }
    olist.push(obj)
 } 
 $.ajax({
    url: url_prefix + "SetPolygonInfo",
    data: ({
        'id': id,
        'poly_points': JSON.stringify(olist),
        'as_json': 1
    }),
    async: false,
    dataType: "json",
    success: function(result) {
        html = result.html;
    },
    error: function(data, status, e) {
        alert(e);
    }
});
return html;
 }

它工作正常。JSON.stringify(poly_points)有时会给出k和A

 [{"k":47.53208121578362,"A":7.705052197034092},
  {"k":47.53188401121172,"A":7.704971730763646}, 
  {"k":47.53189169452062,"A":7.705076336915226}]

但有时它给出

 [{"k":47.53208121578362,"B":7.705052197034092},
  {"k":47.53188401121172,"B":7.704971730763646}, 
  {"k":47.53189169452062,"B":7.705076336915226}]

所以我不希望我的对象/返回列表依赖于变量