Dart decode escaped JSON

Viewed 2143

I'm trying to deserialize a simple JSON object from an API.
The API returns the JSON in escaped quotes since the data represents a user's quote.

test("escaped quoted json test", () {
  var s = '''{"quote": "\"a quote from a user\""}''';

  var b = json.decode(s);
  expect(b["quote"], "\"a quote from a user\"");
});

However this throws:

FormatException: Unexpected character (at character 13)
{"quote": ""a quote from a user""}

Btw the JSON is valid:

{"quote": "\"a quote from a user\""}

enter image description here

How do I tell Dart to handle this correctly?

Thanks in advance.

1 Answers

The inner quote needs to be escaped with a literal backslash not an escaped backslash

var s = '''{"quote": "\\"a quote from a user\\""}''';

or

var s = r'''{"quote": "\"a quote from a user\""}''';

There is a difference between JSON written in Dart source code and JSON received over network.
If you put it in source like in your question, the string is interpreted. You can either adapt the string (double all \) or prefix it with r for raw string.

Related