`rawString()` produces invalid JSON — dict keys and string values containing `"`, newlines, or control chars are not escaped · Issue #1200 · SwiftyJSON/SwiftyJSON · GitHub
Skip to content

rawString() produces invalid JSON — dict keys and string values containing ", newlines, or control chars are not escaped #1200

Open

Description

@tsushanth

Bug

`rawString([.castNilToNSNull: true])` (and `rawString()` generally) can produce invalid JSON for two reasons:

1. Dict keys are interpolated unescaped

In `Source/SwiftyJSON/SwiftyJSON.swift` (around line 600), dictionary keys are written as:

```swift
""(key)": ..."
```

A key containing a double-quote or newline (both valid Swift `String` values) produces output like:

```json
{"key with "quotes"": 1} // invalid JSON
{"key with
newline": 1} // invalid JSON
```

2. String values escape only `\` and `"`, not control characters

Around line 610 (dict) and 641 (array), string values escape `\` → `\\` and `"` → `\"` but leave control characters (`\n`, `\t`, `\r`, U+0000–U+001F) unescaped. Per RFC 8259 §7, all control characters must be escaped in JSON strings.

```swift
let str = JSON(["msg": "line1\nline2"])
print(str.rawString()!)
// {"msg": "line1
// line2"} ← bare newline, invalid JSON — JSONSerialization.jsonObject rejects this
```

Impact

`JSON(obj: [String: Any]).rawString()` silently produces output that:

  • Fails `JSONSerialization.jsonObject(with:)` round-trip
  • Breaks any downstream JSON parser that enforces the spec

Existing partial fix

Closed-unmerged PR #1198 attempted to fix key-quoting but didn't cover control characters and was never merged. Open issue #746 is a different path (`.string` accessor). Neither addresses the control-character gap.

Fix

Route `rawString` output through `JSONSerialization` (which handles escaping correctly), or at minimum escape keys the same way values are escaped, and add `\n`→`\\n`, `\t`→`\\t`, `\r`→`\\r`, and `\u{XX}`→`\\u00XX` for control chars in both keys and values.

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