英文:
how to print pretty json string for data in swift
问题
extension Encodable {
    /// 将 JSON 数据格式化为字符串
    var jsonString: String? {
        let encoder = JSONEncoder()
        encoder.dateEncodingStrategy = .iso8601
        encoder.outputFormatting = .prettyPrinted
        let jsonString = try! encoder.encode(self)
        return String(decoding: jsonString, as: UTF8.self)
    }
}
struct Foo: Codable {
    let string1: String
    let string2: String
    let val: Int
}
let foo = Foo(string1: "string1", string2: "string2", val: 42)
print(foo.jsonString)
//
// "{\n    \"string1\": \"string1\",\n    \"string2\": \"string2\",\n    \"val\": 42\n}"
英文:
I would like to log payload into a pretty print format however, based on my following code. I still see \". how can I make the output like pretty json string format?
"{
    "string1":"string1",
    "string2":"string2",
    "val":42
    }"
extension Encodable {
    /// format the json data to string
    var jsonString: String? {
        let encoder = JSONEncoder()
        encoder.dateEncodingStrategy = .iso8601
        encoder.outputFormatting = .prettyPrinted
        let jsonString = try! encoder.encode(self)
        return String(decoding: jsonString, as: UTF8.self)
    }
}
struct Foo: Codable {
    let string1: String
    let string2: String
    let val: Int
}
let foo = Foo(string1: "string1", string2: "string2", val: 42)
print(foo.jsonString)
//
// "{\"string1\":\"string1\",\"string2\":\"string2\",\"val\":42}"
答案1
得分: 2
你看到 \" 是因为你正在打印一个 Optional。在打印 Optional 时,它会显示该可选容器中保存的字符串文字,该文字将用 " 引用,因此内容也被转义,就像在代码中编写一样。
Optional("{\n  \"string2\" : \"string2\",\n  \"val\" : 42,\n  \"string1\" : \"string1\"\n}")
如果你将打印语句替换为
print(foo.jsonString ?? "")
你将看到字符串内容:
{
  "string2" : "string2",
  "string1" : "string1",
  "val" : 42
}
英文:
You see \" because you are printing an Optional. When printing Optional, it shows you the string literal held by this optional container, which will be quoted in ", so the content is escaped as well, like when you write it in code.
Optional("{\n  \"string2\" : \"string2\",\n  \"val\" : 42,\n  \"string1\" : \"string1\"\n}")
If you replace the print statement with
print(foo.jsonString ?? "")
You will see the string content:
{
  "string2" : "string2",
  "string1" : "string1",
  "val" : 42
}
答案2
得分: 0
混淆发生是因为您指定了错误的返回类型。
由于您明确返回一个非可选字符串,请在声明行中删除问号
var jsonString: String {
您可以通过在print行中强制解包jsonString来获得相同的结果
print(foo.jsonString!)
但更改返回类型是更好的选择。
英文:
The confusion happens because you specified the wrong return type.
As you clearly return a non-optional string remove the question mark in the declaration line
var jsonString: String {
You get the same by force unwrapping jsonString in the print line
print(foo.jsonString!)
but changing the return type is the better choice.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。


评论