将 url 字符串编码为字典 在我的例子中:一些值在里面有 =
Encode url string to Dictionary In my case: Some value have = inside
我正在尝试将下面的 url 编码字符串解码为字典。下面给出了这样做的正常方法。就我而言,它不起作用。我还需要删除 \u{05}
之类的任何字符
let params = str.components(separatedBy: "&").map({
[=11=].components(separatedBy: "=")
}).reduce(into: [String:String]()) { dict, pair in
if pair.count == 2 {
dict[pair[0]] = pair[1]
}
}
我的url编码字符串是
"id=sfghsgh=sbfsfhj&name=awsjdk_fs\u{05}"
我期待结果
{
"id" = "sfghsgh=sbfsfhj",
"name" = "awsjdk_fs"
}
如何实现?
搭载在URLComponents
上:
var components = URLComponents()
components.query = "id=sfghsgh=sbfsfhj&name=awsjdk_fs"
components.queryItems
// => Optional([id=sfghsgh=sbfsfhj, name=awsjdk_fs])
let list = components.queryItems?.map { ([=10=].name, [=10=].value) } ?? []
// [("id", Optional("sfghsgh=sbfsfhj")), ("name", Optional("awsjdk_fs"))]
let dict = Dictionary(list, uniquingKeysWith: { a, b in b })
// ["name": Optional("awsjdk_fs"), "id": Optional("sfghsgh=sbfsfhj")]
如果您需要 [String: String]
而不是 [String: String?]
:
let list = components.queryItems?.compactMap { ([=11=].name, [=11=].value) as? (String, String) } ?? []
// [("id", "sfghsgh=sbfsfhj"), ("name", "awsjdk_fs")]
let dict = Dictionary(list, uniquingKeysWith: { a, b in b })
// ["name": "awsjdk_fs", "id": "sfghsgh=sbfsfhj"]
我正在尝试将下面的 url 编码字符串解码为字典。下面给出了这样做的正常方法。就我而言,它不起作用。我还需要删除 \u{05}
let params = str.components(separatedBy: "&").map({
[=11=].components(separatedBy: "=")
}).reduce(into: [String:String]()) { dict, pair in
if pair.count == 2 {
dict[pair[0]] = pair[1]
}
}
我的url编码字符串是
"id=sfghsgh=sbfsfhj&name=awsjdk_fs\u{05}"
我期待结果
{
"id" = "sfghsgh=sbfsfhj",
"name" = "awsjdk_fs"
}
如何实现?
搭载在URLComponents
上:
var components = URLComponents()
components.query = "id=sfghsgh=sbfsfhj&name=awsjdk_fs"
components.queryItems
// => Optional([id=sfghsgh=sbfsfhj, name=awsjdk_fs])
let list = components.queryItems?.map { ([=10=].name, [=10=].value) } ?? []
// [("id", Optional("sfghsgh=sbfsfhj")), ("name", Optional("awsjdk_fs"))]
let dict = Dictionary(list, uniquingKeysWith: { a, b in b })
// ["name": Optional("awsjdk_fs"), "id": Optional("sfghsgh=sbfsfhj")]
如果您需要 [String: String]
而不是 [String: String?]
:
let list = components.queryItems?.compactMap { ([=11=].name, [=11=].value) as? (String, String) } ?? []
// [("id", "sfghsgh=sbfsfhj"), ("name", "awsjdk_fs")]
let dict = Dictionary(list, uniquingKeysWith: { a, b in b })
// ["name": "awsjdk_fs", "id": "sfghsgh=sbfsfhj"]