我需要从一个特定的字符串中提取 json,如下所示:
'loglocale=
{
"seed": "pqr",
"pageHashCode": "xxx",
"timestamp": 1553589859880,
"channel": "mobile",
"serviceVersion": "1.0",
"language": "en-CHN"
}
; regStatus=xx; s_dslv=34; s_fid=65-64748; s_vn=64678%26vn%3D1',
groups: undefined ]
我已经尝试过,但无法提取它。
var regex=cookies.match(/{"seed":(\w|\W)*"channel":(\w|\W)*}/);
我可以使用什么解决方案? 预先感谢:)
最佳答案
如果您知道字符串中只有一个像这样的纯 JSON 对象,则可以使用此正则表达式来捕获大括号及其之间的所有内容:
const curlyBracesInclusive = /\{([^}]+)\}/
const arr = string.match(curlyBracesInclusive)
// arr[0] will be a the JSON string, if one was found
这并不能保证字符串是有效的 JSON。因此,如果您想对结果运行 JSON.parse
,请注意,如果字符串无效,它将抛出错误。
关于javascript - 如何从javascript中的字符串中提取json,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59229465/