Description
The hand-rolled serializer in _rawString(...) used when the option .castNilToNSNull: true is set produces malformed JSON two ways: dictionary keys are interpolated completely unescaped, and string values escape only backslash and double-quote, so control characters (newline, tab, and the U+0000 to U+001F range) are not escaped, which JSON forbids.
Steps to reproduce (compiled against the real source)
- a key containing a double-quote, e.g.
["a\"b": 1], produces {"a"b": 1} (invalid: unescaped quote in key)
- a key containing a newline produces a literal newline inside the key (invalid control character)
- a value containing a newline, e.g.
["k": "line1\nline2"], emits a literal newline inside the string (invalid)
All three fail to re-parse via JSONSerialization ("Unescaped control character" / "not in the correct format").
Root cause
Source/SwiftyJSON/SwiftyJSON.swift: keys are interpolated raw ("\"\(key)\": ..." -- key is never escaped), and value escaping via replacingOccurrences covers only backslash and double-quote, in both the dictionary and array branches.
Suggested fix
Escape keys with the same logic used for values, and extend value escaping to cover control characters (\n \r \t \b \f and \u00XX for the rest) -- or route this path through JSONSerialization. (Note: closed-unmerged PR #1198 attempted the key-quote facet only, not control characters.)
Description
The hand-rolled serializer in
_rawString(...)used when the option.castNilToNSNull: trueis set produces malformed JSON two ways: dictionary keys are interpolated completely unescaped, and string values escape only backslash and double-quote, so control characters (newline, tab, and the U+0000 to U+001F range) are not escaped, which JSON forbids.Steps to reproduce (compiled against the real source)
["a\"b": 1], produces{"a"b": 1}(invalid: unescaped quote in key)["k": "line1\nline2"], emits a literal newline inside the string (invalid)All three fail to re-parse via
JSONSerialization("Unescaped control character" / "not in the correct format").Root cause
Source/SwiftyJSON/SwiftyJSON.swift: keys are interpolated raw ("\"\(key)\": ..."--keyis never escaped), and value escaping viareplacingOccurrencescovers only backslash and double-quote, in both the dictionary and array branches.Suggested fix
Escape keys with the same logic used for values, and extend value escaping to cover control characters (
\n \r \t \b \fand\u00XXfor the rest) -- or route this path throughJSONSerialization. (Note: closed-unmerged PR #1198 attempted the key-quote facet only, not control characters.)