简体   繁体   English

如何在PHP中“作为JSON”读取抓取的JavaScript对象文字(带有未加引号的键)?

[英]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);

Regex101.com Regex101.com

PHP Sandbox PHP沙箱

Edit 编辑

For the supplied string, you need to check two more things: 对于提供的字符串,您需要再检查两件事:

  • Make sure that the pattern isn't in a string (eg. "Your selection: {packageName}" ) 确保模式不在字符串中(例如, "Your selection: {packageName}"
  • Make sure that the backslash character is escaped ( Source ) 确保反斜杠字符已转义( Source

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM