Mu Mind
Mu Mind

Reputation: 11194

How can I parse JSON-like syntax that uses single quotes?

The JSON standard says strings must be delimited by double quotes, but people insist on passing around data in a format that's identical to JSON except for using single quotes to delimit strings.

What's the simplest way to safely decode strings like this

{'foo': null, 'bar': "Mac 'n Cheese"}

into a python structure like

{'foo': None, 'bar': "Mac 'n Cheese"}

Approaches that will not work are using ast.literal_eval (it doesn't understand null) or just using regexes to replace all single-quotes with double-quotes (strings won't be escaped properly).

Note: I'm well aware this is not JSON (as has been pointed out ad nauseam on several similar questions), but I need to be able to interact with sloppy APIs that produce data like this.

Upvotes: 2

Views: 262

Answers (1)

user2357112
user2357112

Reputation: 280564

A quick Google search turned up demjson, a JSON parser for Python with a non-strict mode capable of handling this format.

Upvotes: 2

Related Questions