How to parse JSON with unquoted keys in Java

I’m working with an API that returns JSON data where some property names don’t have quotes around them. For example, instead of getting {"status": "success"}, I receive something like {status: "success"}.

I’ve heard this format is called relaxed JSON or loose JSON. The issue is that standard JSON parsers in Java throw errors when they encounter unquoted keys. I tried using Jackson and Gson, but both fail to parse this format.

Here’s an example of what I’m receiving:

{name: "John Smith", age: 25, active: true}

Instead of the standard format:

{"name": "John Smith", "age": 25, "active": true}

Is there a way to handle this type of JSON parsing in Java? Are there any libraries that support relaxed JSON format, or do I need to preprocess the data somehow before parsing it?

Had this exact issue with a legacy API last year. The Jackson solution works great, but if you’re stuck with Gson, just preprocess the JSON string with regex before parsing. Use jsonString.replaceAll("(\\w+):", "\"$1\":") to add quotes around unquoted keys. Not pretty, but it saved my ass when I couldn’t switch libraries mid-project. Watch out for nested objects though, and make sure your regex doesn’t quote already quoted keys.

Jackson’s JsonFactory handles this too with JsonReadFeature.ALLOW_UNQUOTED_FIELD_NAMES in newer versions. I ran into this with config files that weren’t strict JSON. Just watch out for edge cases - these relaxed formats often have trailing commas or other weird stuff. If you’re preprocessing, use a proper tokenizer instead of regex. Regex breaks on nested structures or strings with colons. You could also try the JSON5 library - it’s built for extended JSON syntax, but you’ll add another dependency.

try jackson with JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES enabled. just configure your ObjectMapper like mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true) and it’ll handle unquoted keys. worked for me in a similar situation.

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.