[英]How can I extract a json from a string in javascript
我需要從如下所示的特定字符串中提取 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)*}/);
我可以使用的解決方案是什么? 提前致謝:)
對於日志語言環境:
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 ]`
然后:
let string = dataJSON.substring(
dataJSON.indexOf("loglocale=") + 10,
dataJSON.lastIndexOf("; regStatus")
)
JSON.parse(string);
如果您知道字符串中只有一個像這樣的純 JSON 對象,您可以使用此正則表達式來捕獲花括號及其之間的所有內容:
const curlyBracesInclusive = /\{([^}]+)\}/
const arr = string.match(curlyBracesInclusive)
// arr[0] will be a the JSON string, if one was found
這無法保證字符串是有效的 JSON。 因此,如果您想對結果運行JSON.parse
,請注意,如果字符串無效,它將引發錯誤。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.