简体   繁体   中英

Proper way to deal with string which looks like json object but it is wrapped with single quote

By definition the JSON string is wrapped with double quote.

In fact:

json.loads('{"v":1}') #works

json.loads("{'v':1}") #doesn't work

But how to deal with the second statements? I'm looking for a solution different from eval or replace. Thanks.

If you get a mailformed json why don't you just replace the double quotes with single quotes before

json.load

If you cannot fix the other side you will have to convert invalid JSON into valid JSON. I think the following treats escaped characters properly:

def fixEscapes(value):
  # Replace \' by '
  value = re.sub(r"[^\\]|\\.", lambda match: "'" if match.group(0) == "\\'" else match.group(0), value)
  # Replace " by \"
  value = re.sub(r"[^\\]|\\.", lambda match: '\\"' if match.group(0) == '"' else match.group(0), value)
  return value

input = "{'vt\"e\\'st':1}"
input = re.sub(r"'(([^\\']|\\.)+)'", lambda match: '"%s"' % fixEscapes(match.group(1)), input)
print json.loads(input)

Not sure if I got your requirements right, but are you looking for something like this?

def fix_json(string_):
    if string_[0] == string_[-1] == "'":
        return '"' + string_[1:-1] +'"'
    return string_

Example usage:

>>> fix_json("'{'key':'val\"'...cd'}'")
"{'key':'val"'...cd'}"

EDIT: it seems that the humour I tried to have in making the example above is not self-explanatory. So, here's another example:

>>> fix_json("'This string has - I'm sure -  single quotes delimiters.'")
"This string has - I'm sure -  single quotes delimiters."

This examples show how the "replacement" only happens at the extremities of the string, not within it.

you could also achieve the same with a regular expression, of course, but if you are just checking the starting and finishing char of a string, I find using regular string indexes more readable....

unfortunately you have to do this:

f = open('filename.json', 'rb')

json = eval(f.read())

done!

this works, but apparently people don't like the eval function. Let me know if you find a better approach. I used this on some twitter data...

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