[英]How to read a scraped JavaScript object literal (with unquoted keys) “as JSON” in PHP?
I have a json object scraped from a website 我有一个从网站抓取的json对象
{
area: {
"lang": "en",
"area": "25",
"region": "mea"
},
config: {
"rtl": false,
"breakpoint": 768
}
}
due to the season area and config is not enclosed in double quotes php function json_decode retuerns NULL 由于季节区域和配置未用双引号引起来php函数json_decode retuerns NULL
how to add double quotes in php to area and config if these are not already enclosed in double quotes? 如果尚未将双引号括在双引号中,如何在php中将双引号添加到区域和配置中?
Use a regex replace, (assuming the format). 使用正则表达式替换(假定格式)。
$json = preg_replace('/([^"\s]+)+: ?{/', '"$1": {', $js_object);
For the supplied string, you need to check two more things: 对于提供的字符串,您需要再检查两件事:
"Your selection: {packageName}"
) "Your selection: {packageName}"
) Here's the updated code: 这是更新的代码:
$js_object = '...';
$json_proper_backslashes = preg_replace('#\\\\([^"\\\\\/bfnrtu])#', '\\\\\\\\$1', $js_object);
$json = preg_replace('/({|},)\s*([^"\s]+): ?{/', '$1"$2": {', $json_proper_backslashes);
$json_object = json_decode($json);
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.