简体   繁体   中英

How to read a scraped JavaScript object literal (with unquoted keys) “as JSON” in PHP?

I have a json object scraped from a website

{
    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

how to add double quotes in php to area and config if these are not already enclosed in double quotes?

Use a regex replace, (assuming the format).

$json = preg_replace('/([^"\s]+)+: ?{/', '"$1": {', $js_object);

Regex101.com

PHP Sandbox

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}" )
  • Make sure that the backslash character is escaped ( 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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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