javascript - 从无效 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() 是否不正确。任何纠正此问题的帮助表示赞赏:)
解决方案
您的输入不是有效的 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);
推荐阅读
- google-cloud-functions - 如何获取违反 Stackdriver 提醒政策的 Cloud Functions 的日志?
- c# - C# 将 ListBox.SelectedItems 复制到另一个变量
- python - 循环通过 Base64 txt 文件批量转换为图像?
- react-select - 如何将 data-testid 属性添加到 react-select 组件
- javascript - 尝试在 foreach 循环内将一些 javascript 嵌入到 laravel 视图中
- python - 如何使用带有apollo-upload-client的graphene-file-upload将graphql中的文件上传到Python数据库并在前端做出反应。?
- python - 管理员端修改django
- mysql - sum 函数返回错误的值
- azure-devops - 有没有办法使用证书运行此 Azure Key Vault 任务(在 Azure DevOps 中)?
- php - 如何在 FullCalendar v4 中使用时间数据类型从数据库中获取事件