Sign up ×
Stack Overflow is a community of 4.7 million programmers, just like you, helping each other. Join them; it only takes a minute:

I want to store some regex string in a json file, then use python to parse json file. however, as the regex backslash will be treated as invalid in json. so How should I do.

{
    "key" : "^https://www\.google\.com/search?.+",
    "value" : "google"
}

As you can see above, As regular expression, some fullstop (?.+) will be regex, some will be just fullstop (.), however, this json file will not be thought as valid. So how should I do.

Thanks!

share|improve this question
    
Escape your characters See: stackoverflow.com/questions/280435/… – Bart Vanherck Mar 19 '14 at 6:25

3 Answers 3

up vote 0 down vote accepted

Add one more back slash for each and every back slash .

        str=str.replace("\", "\\");

add above code into code before json usage..!

       {
          "key": "^https://www\\.google\\.com/search?.+",
          "value": "google"
       }

Its valid one..!

HOpe it helps...!

share|improve this answer
    
Thanks Sidharthan, I think your solution is clean, and I do not need use replace(), just use \\ instead of \ in file. – Jerry YY Rain Mar 19 '14 at 7:29

You need to use escape the backslashes for the regex, and then escape them again for the string processor:

>>> s = """{
...     "key" : "^https://www\\\\.google\\\\.com/search?.+",
...     "value" : "google"
... }"""
>>> json.loads(s)
{'key': '^https://www\\.google\\.com/search?.+', 'value': 'google'}

If you're going the other way, i. e. from a Python dictionary that contains a regex string to a JSON object, the encoder will handle this for you, but it's a good idea in general to use raw strings for regexes:

>>> s = """{
...     "key" : "^https://www\.google\.com/search?.+",
...     "value" : "google"
... }"""
>>> json.dumps(s)
'"{\\n    \\"key\\" : \\"^https://www\\\\.google\\\\.com/search?.+\\",\\n    \\"value\\" : \\"google\\"\\n}"'
share|improve this answer

You need to escape the backslashes when generating the JSON string. Whatever tool you use to generate the JSON probably has that built in. For example, with the Python json module:

>>> print json.dumps({'asdf': r'\s+'})
{"asdf": "\\s+"}

Note that the output has two backslashes in it. When parsed, those will become one backslash.

share|improve this answer
    
If I need read json from a file, how to use r'\s+' – Jerry YY Rain Mar 19 '14 at 6:59
    
@Jerry: If you're reading JSON from a file, then either everything has already been handled for you, or the data source is broken. – user2357112 Mar 19 '14 at 7:02

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.