如何在对象内部获取数组,删除双引号并将其作为对象放入 JSON 语法中

how to get arrays inside objects , remove double quotes and make it as an object to put inside json syntax

本文关键字:对象 语法 JSON 获取 内部 数组 删除      更新时间:2023-09-26

我像这样制作jsonstring:

  { "dataTarget":["[Date.UTC(2016,3,01),10.00]",
                  "[Date.UTC(2016,1,01),5.00]"],
     "dataRealisasi" :["[Date.UTC(2016,3,01),10.00]",
                      "[Date.UTC(2016,1,01),5.00]"]
     }

我通过jquery ajax检索它并解析它

 var dataChart =  JSON.parse(msg.d);                   
 var dataTarget = dataChart['dataTarget']
 var dataRealisasi = dataChart['dataRealisasi']

i控制台日志数据目标,结果如下:

["[Date.UTC(2016,3,01),10.00]", "[Date.UTC(2016,1,01),5.00]"]

我需要的是一个这样的变量

[
[Date.UTC(2016,3,01),10.00],
[Date.UTC(2016,1,01),5.00]
]

我可以将其作为变量传递到此

  $('#container3').highcharts({
    chart: {
        type: 'spline'
    },
    title: {
        text: 'Monitoring Proyek'
    },
    subtitle: {
        text: 'Proyek'
    },
    xAxis: {
        type: 'datetime',
        dateTimeLabelFormats: { // don't display the dummy year
            month: '%e. %b',
            year: '%b'
        },
        title: {
            text: 'Date'
        }
    },
    yAxis: {
        title: {
            text: 'Target (%)'
        },
        min: 0
    },
    tooltip: {
        headerFormat: '<b>{series.name}</b><br>',
        pointFormat: '{point.x:%e. %b}: {point.y:.2f} %'
    },
    plotOptions: {
        spline: {
            marker: {
                enabled: true
            }
        }
    },
    series:  [{
        "name": "Proyeksi Target",          
        "data":  dataTarget // this is the variable

    }, {
        name: 'Realisasi',
        data: 
           dataRealisasi // this is the variable
    }]
     });

更新:问题是当我创建没有双引号的 JSON 字符串时,然后 JSON.parse 它会返回错误......我已经更改了服务器端函数并返回对象:

[["Date.UTC(2016,3,01)",10.00], ["Date.UTC(2016,1,01)",5.00]] 

,现在我需要删除双引号并更改它:

[[Date.UTC(2016,3,01),10.00], [Date.UTC(2016,1,01),5.00]]

在这里需要帮助...

你可以像这样转换json(不要使用eval(:

[
    "[Date.UTC(2016,3,01),10.00]", 
    "[Date.UTC(2016,1,01),5.00]"
].map(function(v){
    return new Function('return ' + v)();
});

但强烈建议您只使用时间戳,因为此转换的成本比平时要高一些

不知道前导 0,所以我会把它清理掉

 // the data 
var data = [
    "[Date.UTC(2016,3,01),10.00]", 
    "[Date.UTC(2016,1,01),5.00]"
];
var clean = function(n){  // remove leadin zero as we want the numbers.
  return Number(n.replace(/^0+?/, ""));
}
// removes unneeded characters "Date.UTC(", ")","[","]"
// split to an array of strings. Clean of leading zeros ? and convert to numbers
var convert = function(str){
  var n = str.replace(/Date.UTC'(|')|'[|']/g, "").split(",").map(clean);
  return [Date.UTC(n[0], n[1], n[2]), n[3]]; // get date and return the array item as an array
}
// Start the ball rolling.
try{
    data = data.map(convert);
}catch(e){
    console.log("You are having a bad day!");
}
// data === [[1459468800000, 10], [1454284800000, 5]];