🪞 Formatter JSON delightfully.
Add https://github.com/luin/SwiftJSONFormatter
in the “Swift Package Manager” tab in Xcode.
After import SwiftJSONFormatter
, you can access two static methods for beautifying and minifying.
import SwiftJSONFormatter
SwiftJSONFormatter.beautify("{\"name\":\"Bob\"}")
// String output:
// {
// "name": "Bob"
// }
By default, each level is indented by two spaces. You can customize it with the indent
option:
import SwiftJSONFormatter
SwiftJSONFormatter.beautify("{\"name\":\"Bob\"}", indent: " ")
// String output:
// {
// "name": "Bob"
// }
import SwiftJSONFormatter
SwiftJSONFormatter.minify("""
{
"name": "Bob"
}
""")
// String output:
// {"name":"Bob"}
In some cases, you can leverage a JSON parser to parse your JSON string to a Swift data structure
and then encode it to a string with JSONEncoder
and the .prettyPrinted
option.
However, it comes with two drawbacks:
Dictionary key order are changed randomly everytime.
Swift dictionary, by nature, are not designed to be ordered. That means everytime you encode your JSON data back to a string, the result may be much different from the original one.
Whereas this libaray guarantees the dictionary key orders are not changed after formatting.
Doesn't work with invalid JSON data.
This library makes a best effort to format invalid JSON data. It handles cases such as unterminated strings, trailing commas without issues.
These two drawbacks are non trivial when you are, for example, writing a JSON editor that accepts user inputs. You don't want dictionary key orders change on each formatting, nor the formatter suddenly doesn't work at all when users enter a trailing commas.
No. This library is not a JSON parser so here are what it cannot do:
You'll need to find a real one like SwiftyJSON if those are what you need.
link |
Stars: 11 |
Last commit: 5 weeks ago |
Support Unicode sequence escaping
Swiftpack is being maintained by Petr Pavlik | @ptrpavlik | @swiftpackco | API | Analytics