Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/regex/16.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何从javascript中的字符串提取json_Javascript_Regex - Fatal编程技术网

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

如何从javascript中的字符串提取json,javascript,regex,Javascript,Regex,我需要从一个特定字符串中提取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=6467

我需要从一个特定字符串中提取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 ]`

然后:

对于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 ]`

然后:


如果您知道字符串中只有一个类似这样的纯JSON对象,那么可以使用此正则表达式捕获大括号以及介于两者之间的所有内容:

const curlyBracesInclusive = /\{([^}]+)\}/
const arr = string.match(curlyBracesInclusive)
// arr[0] will be a the JSON string, if one was found

这并不能保证字符串是有效的JSON。因此,如果要对结果运行
JSON.parse
,请注意,如果字符串无效,它将抛出错误

如果您知道字符串中只有一个这样的纯JSON对象,那么可以使用此正则表达式来捕获大括号以及介于两者之间的所有内容:

const curlyBracesInclusive = /\{([^}]+)\}/
const arr = string.match(curlyBracesInclusive)
// arr[0] will be a the JSON string, if one was found

这并不能保证字符串是有效的JSON。因此,如果要对结果运行
JSON.parse
,请注意,如果字符串无效,它将抛出错误

是前面的
后面的东西实际上是字符串的一部分?您有权访问实际的JSON数据吗?如果可能的话,最好使用
JSON.parse
而不是regex。您可以使用
JSON.parse(s.match(/({.+?})/ms)[0])
如果字符串与您的帖子一样是逐字的。是前面的
后面的内容实际上是字符串的一部分?您有权访问实际的JSON数据吗?如果可能的话,最好使用
JSON.parse
而不是regex。您可以使用
JSON.parse(s.match(/({.+?})/ms)[0])如果字符串与您的帖子中的一样是逐字输入的。