Skip to content

rawString([.castNilToNSNull: true]) emits invalid JSON - unescaped keys and unescaped control characters #1199

Description

@tsushanth

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.)

Activity

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

      Milestone

      No milestone

      Relationships

      None yet

      Development

      No branches or pull requests

      Issue actions