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 { "name": "value" }, I get something like { name: "value" }.

I believe this format is known as relaxed JSON. When I try to use standard Java JSON libraries to parse it, I encounter errors because they require proper JSON syntax with quoted keys.

String apiResponse = "{status: 'success', data: {count: 42, items: ['apple', 'banana']}}";

// This fails with standard JSON parsers
ObjectMapper mapper = new ObjectMapper();
JsonNode result = mapper.readTree(apiResponse); // throws exception

What’s the best way to manage this kind of response in Java? Are there libraries available that can interpret relaxed JSON format, or do I need to modify the string before parsing it?

You could also try org.json library - it’s pretty relaxed by default and doesn’t need special configs like Jackson or Gson. Just do new JSONObject(apiResponse) and it’ll handle unquoted keys no problem. Not as feature-rich, but perfect for simple parsing.

Jackson handles this out of the box if you set it up right. Just enable ALLOW_UNQUOTED_FIELD_NAMES on your ObjectMapper. Had the same problem with a legacy system spitting out bad JSON.

ObjectMapper mapper = new ObjectMapper();
mapper.configure(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES, true);
mapper.configure(JsonParser.Feature.ALLOW_SINGLE_QUOTES, true);
JsonNode result = mapper.readTree(apiResponse);

The second line handles single quotes around strings, which looks like what you’ve got too. This worked great for me and beat having to preprocess the string or find another library. Just heads up - these settings make your parser less strict, so maybe use a separate ObjectMapper just for this API so you don’t accidentally accept garbage JSON somewhere else.

Gson works great for this. Had the same problem with a third-party service that was sloppy with JSON formatting. Gson’s lenient mode handles unquoted keys and other weird JSON stuff without breaking.

Gson gson = new GsonBuilder().setLenient().create();
JsonReader reader = new JsonReader(new StringReader(apiResponse));
reader.setLenient(true);
JsonElement result = gson.fromJson(reader, JsonElement.class);

The setLenient() calls make Gson way more forgiving with broken JSON. Way easier than messing with Jackson configs. Performance’s fine unless you’re parsing tons of data. Just watch out - lenient parsing can hide real data quality problems from your API provider.