php - 修复无效的 JSON
问题描述
我有一个巨大的文件,不幸的是包含无效的 JSON。它看起来像数组列表,没有用逗号分隔:
[{
"key": "value"
}]
[
[{
"key": "value",
"obj": {}
},
{}
]
]
[{
"key": "value",
"obj": {}
}]
每个方括号对内的内容本身似乎是一个有效的 JSON。
问题是如何使用“搜索和替换”快速修复这个 JSON?(或任何其他方法)
尝试了许多组合,包括将“ ][ ”替换为“ ],[ ”,并用另一个方括号对包装整个文件,使其成为数组数组。每次它给我无效的JSON。
请帮忙。
解决方案
You can replace the closing brackets with '],' and wrap the entire string in brackets.
This snippet illustrates the method with the supplied sample data by applying the algorithm and then calling eval on the resulting string.
let jsonString = `[{
"key": "value"
}]
[
[{
"key": "value",
"obj": {}
},
{}
]
]
[{
"key": "value",
"obj": {}
}]`;
jsonString = jsonString.replace( /]/g, '],' );
jsonString = '[' + jsonString + ']';
myObject = eval( jsonString );
console.log( typeof myObject);
console.log( myObject.length );
console.log( myObject );
推荐阅读
- c# - 使用 libgit2sharp 做“git log”
- java - 从java执行批处理文件时行为不一致
- testing - 使用 Testcafe 选择器:withText 然后兄弟
- jax-rs - 为什么这个 JAX-RS 404 响应得到一个空的正文?
- spotfire - 使用 Spotfire 中列中的数据在交叉表中创建列名?
- html - Office UI Fabric 的布局问题
- r - R编程:如何根据给定的纬度和经度将二维数组重塑为3维数组?
- linux - 为什么不同 Linux 操作系统但在相同硬件上的上下文切换时间不同?
- swift - 来自 notification.userInfo 的数据
- javascript - 错误声明的价值是增加