json – Grey Panthers Savannah https://grey-panther.net Just another WordPress site Tue, 27 Dec 2011 11:40:00 +0000 en-US hourly 1 https://wordpress.org/?v=6.7.1 206299117 Relaxed JSON parsing https://grey-panther.net/2011/12/relaxed-json-parsing.html https://grey-panther.net/2011/12/relaxed-json-parsing.html#respond Tue, 27 Dec 2011 11:40:00 +0000 https://grey-panther.net/?p=36 This blogpost was originally posted to the Transylvania JUG blog.

JSON is a good alternative when you need a lightweight format to specify structured data. But sometimes (for example when you want the user to specify JSON manually) you would like to relax the formalism required to specify "valid" JSON data. For example the following snippet is not valid as per the spec, although its intent is quite clear:

[{ foo: 'bar' }]

To make this standard compliant we would need to write it as:

[{ "foo": "bar" }]

We shouldn’t run out and blame the standard of course since it needs to balance many contradictory requirements (ambiguity of encoded data, ease of understanding, ease of writing parsers, etc). If you decide that you want to strike the balance differently (make the definition of valid data more relaxed) you can do this easily with the Jackson parser:

JsonParser parser = new JsonFactory()
	.createJsonParser("[{ foo: 'bar' }]")
		.enable(JsonParser.Feature.ALLOW_UNQUOTED_FIELD_NAMES)
		.enable(JsonParser.Feature.ALLOW_SINGLE_QUOTES);
JsonNode root = new ObjectMapper().readTree(parser);

assertEquals("bar", root.get(0).get("foo").asText());

If your tool of choice is gson, it is slightly more complicated but still doable. See the linked source code for a complete example.

JSON is a good tool for semi-structured data and using a relaxed parsing can make the programs you write easier to use.

]]>
https://grey-panther.net/2011/12/relaxed-json-parsing.html/feed 0 36