首页 > 解决方案 > 从无效 JSON 的字符串中提取数组

问题描述

我有一个数据对象,它是从某个预定义的数据库表的列中获取的,该列包含两个数组,如下所示:

const distribution_bins = "{[0.0, 0.3, 0.6, 0.9, 1.2, 1.5, 1.8, 2.1, 2.4, 2.7, +INF], [0.0, 0.12, 0.24, 0.36, 0.48, 0.6, 0.72, 0.84, 0.96, +INF]}";

我需要从中提取单独的数组:

 array1 = [0.0, 0.3, 0.6, 0.9, 1.2, 1.5, 1.8, 2.1, 2.4, 2.7, +INF],
 array2 = [0.0, 0.12, 0.24, 0.36, 0.48, 0.6, 0.72, 0.84, 0.96, +INF]

为此,我正在执行这样的操作distribution_bins

console.log(distribution_bins.split('],'));

但这样做会产生如下数据:

[
  '{[0.0, 0.3, 0.6, 0.9, 1.2, 1.5, 1.8, 2.1, 2.4, 2.7, +INF',
  ' [0.0, 0.12, 0.24, 0.36, 0.48, 0.6, 0.72, 0.84, 0.96, +INF]}'
]

]注意第一个数组后面缺少的右括号[0.0, 0.3,....,2.7, +INF'

不确定完成的 split() 是否不正确。任何纠正此问题的帮助表示赞赏:)

标签: javascriptarraysjson

解决方案


您的输入不是有效的 JSON,但很接近。如果您对其有任何控制权,则应将其更改为有效的 Json。如果你不这样做,你可以这样做:

// Create keys for the properties of the objects. This uses the offset
// of the start of the property as its key.
let jsonify = distribution_bins.replace(/{/g, "[");
jsonify = jsonify.replace(/}/g, "]");

// Wrap +INF in quotes.
jsonify = jsonify.replace(/\+INF/g, `"+INF"`);

// Parse.
const distribution_data = JSON.parse(jsonify);

推荐阅读