[SOLVED] jsonEncode vs JSON.stringify - why does dart escape strings?

I’ve come across an issue where my API request bodies are unexpectedly being escaped.

e.g.

jsonEncode( {
        "header": "test \n string",
});

--> '{"header":"test \\n string"}'

In javascript, JSON.stringify does not escape the \n.

I’m confused why dart is escaping strings by default, and can it be turned off?

2 Likes

@joshburton I think you solved this one?

  1. Dart is not JavaScript.

  2. Dart is not JavaScript.

  3. The correct behavior of encoding a String requires \n to be encoded, otherwise:

JavaScript:

{"header": "test 
string"}

Dart (also PHP and everyone else in the Universe that does not have brain damage):

{"header": "test \\n string"}
  1. JSON IS A STRING, not a map! json_annotations package is SOOOOOO wrong in this regard. A map is not a JSON. JSON is always string. Is a TEXT representation of a JavaScript object.

p.s.:

PHP:

<?php
echo(json_encode(array('header' => 'test \n string')));
{"header":"test \\n string"}

Quote from Albert Einstein:

If your language is worst than PHP, then you really need to use something else

3 Likes

@joshburton told on Bluesky that he found the bug in his code :person_shrugging: