[英]How can I extract a json from a string in javascript
I need to extract json from a particular string which looks like this:我需要从如下所示的特定字符串中提取 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 ]
I have tried this but could not extract it .我试过这个,但无法提取它。
var regex=cookies.match(/{"seed":(\w|\W)*"channel":(\w|\W)*}/);
What is the solution I could use?我可以使用的解决方案是什么? Thanks in advance:)
提前致谢:)
For the loglocale:对于日志语言环境:
let dataJSON = `
'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 ]`
then:然后:
let string = dataJSON.substring(
dataJSON.indexOf("loglocale=") + 10,
dataJSON.lastIndexOf("; regStatus")
)
JSON.parse(string);
If you know there is only a single plain JSON object like this in the string, you can use this regex to capture the curly braces and everything in between:如果您知道字符串中只有一个像这样的纯 JSON 对象,您可以使用此正则表达式来捕获花括号及其之间的所有内容:
const curlyBracesInclusive = /\{([^}]+)\}/
const arr = string.match(curlyBracesInclusive)
// arr[0] will be a the JSON string, if one was found
This is no way guarantees the string is valid JSON.这无法保证字符串是有效的 JSON。 So if you want to run
JSON.parse
on the result, be aware it will throw an error if the string is invalid.因此,如果您想对结果运行
JSON.parse
,请注意,如果字符串无效,它将引发错误。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.