正则表达式弄乱了json_decode();

I am using a file containing a json string to create request validations. One of the slices of JSON in one of my tests looks like this:

    {
        "name": "pattern",
        "attributes": [
            {
                "name": "pattern",
                "value": "^[\d]{2}$"
            }
        ]
    }

when you try to use json_decode() on this string however, you get a json syntax error. It has something to do with the content of the regular expression. Why and is there a way around this?

The backslash needs to be escaped:

  "value": "^[\\d]{2}$"

JSON allows the following tokens in strings:

  • any-Unicode-character-except-"-or-\-or-control-character
  • \"
  • \\
  • \/
  • \b
  • \f
  • \t
  • \u four-hex-digits

\d is not allowed.

You need to escape out the \, as \d isn't a valid control character in JSON.