I’m trying to make an app using a specific API, but the problem is the response is quite tricky. Most of the keys and values are inside straight quotes (") except for one. One of the values starts with a curly quote (“) and ends with the straight quote("). Using JSONDecoder and codable is not working.
Any work around for this one without modifying the response on server side?
I tried replacing occurences of curly quotes with straight quotes only to find that some of the values are using curly quotes inside them so it wont work.
2
Answers
You may need to fiddle with regular expressions, things like:
^“
for curly quotes in the start of fields, and“$
for curly quotes in the end of words. This way you can match only curly quotes that start or end key/values of your JSON. It shouldn’t be very complex to pinpoint and replace them with today’s languages support for REGEX and text substitutions.First, you absolutely should fix the server. This is invalid JSON.
If you can’t fix the server, a substitution based on your knowledge of the format is probably the right thing. Look for something like
/“[^"]*"/:
as a regex to look for a smart quote followed by a bunch of non-"
, followed by"
followed immediately by:
. Maybe in your particular case that will happen to work.But these are boring answers. Let’s do it the hard way and validate some JSON by hand, and fix this one special case (smart quote at the beginning of a key).
One tool you could use is a JSON tokenizer. For something fairly off-the-shelf (but not particularly supported), see RNJSON. After importing with:
The following would rewrite your JSON:
RNJSON is a toy of mine (as is the closely related RNAJSON), and I don’t recommend relying on the full package. I recommend just copying what you need and learning from it.
So another way to approach this is to parse it directly. It’s a lot more code, but it’s a good introduction to really simple parsing. This code does not try to carefully validate the JSON. It does the minimum it can to make sure it’s at an object-key before looking for smart-quotes. Other than that, it assumes a later parser will check the details.
The key block of code for this problem is:
Here’s the full function to your specific problem.