0

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?

DMP
  • 523
  • 4
  • 19
  • That's not valid JSON, so it can't be a "json object".. anyway, updated the title to reflect the intent. YMMV. – user2864740 Nov 03 '18 at 05:12
  • Possible duplicate of [Convert invalid json into valid json](https://stackoverflow.com/questions/8815586/convert-invalid-json-into-valid-json) – Dave Nov 03 '18 at 05:45

1 Answers1

1

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);
Community
  • 1
  • 1
Chris Happy
  • 7,088
  • 2
  • 22
  • 49