简体   繁体   English

如何从javascript中的字符串中提取json

[英]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.

相关问题 如何使用 javascript 从 JSON 文件中提取数据? - How can I extract data from a JSON file using javascript? 如何从json localStorage字符串中提取数字值? - How can I extract a number value from a json localStorage string? 如何使用Javascript从字符串中间提取然后重新格式化文本? - How can I extract and then reformat text from the middle of a string with Javascript? 如何从 JavaScript 中的字符串中提取数字? - How can I extract a number from a string in JavaScript? 如何使用Javascript从字符串中间提取文本? - How can I extract text from the middle of a string with Javascript? 如何从查询字符串javascript中提取地址 - How can I extract address from query string javascript 如何用javascript从字符串中提取两个字符串? - How can I extract two strings from a string with javascript? 如何从JavaScript中的URL字符串提取值? - How can I extract values from URL string in JavaScript? 如何从 Javascript 中的字符串中提取 ID - How can I extract the Id from a string in Javascript 如何通过从单独的数组中匹配的字符串对象值从 3 个嵌套的 json 数组中提取对象值,然后在 html/javascript 中显示它 - How can I extract object values from 3 nested json arrays by matched string object values from a separate array and then display it in html/javascript
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM