How to encode and then decode to JSON, to escape meantime the special character?
I have now this code:
let o5: [String: Any] = ..
let o6 = try JSONSerialization.data(withJSONObject: o5, options: JSONSerialization.WritingOptions.prettyPrinted)
let decoder = JSONDecoder()
decoder.dateDecodingStrategy = .iso8601
decoder.keyDecodingStrategy = .useDefaultKeys
let o7 = try decoder.decode(Organization.self, from: o6)
I would do following text replacement: / -> \/, new line -> \n, " -> \".
Recently I have unfortunatelly unescaped special characters in my DB.
Related
let params = [["_event": "bulk-subscribe", "tzID":8, "message":"pid-1175152:"]]
let jParams = try! JSONSerialization.data(withJSONObject: params, options: [])
var jsonString:String = String.init(data: jParams, encoding: .utf8) ?? "err"
The result of the code is to get the following values
[{"_event":"bulk-subscribe","tzID":8,"message":"pid-1175152:"}]
The result I want is the following values. Result value with " added
["{"_event":"bulk-subscribe","tzID":8,"message":"pid-1175152:"}"]
What do I need to fix?
Thank you
Your requested output is an array containing one element, a serialized JSON dictionary.
You get this by creating params as a dictionary
let params : [String:Any] = ["_event": "bulk-subscribe", "tzID":8, "message":"pid-1175152:"]
and wrap the result of the serialization in square brackets. There are no escape characters involved.
let jParams = try! JSONSerialization.data(withJSONObject: params)
let jsonStringArray = [String(data: jParams, encoding: .utf8)!]
I'm trying to encode an integer that starts with a 0 into JSON using swift 4.
I'm using a pretty standard JSONSerialization library, but for some reason, after converting the string to data using utf8, I cannot serialize it.
let code = "012345" // example code
let body = "{\"code\": " + code + "}"
let stringData = body.data(using: .utf8)!
let jsonArray = try? JSONSerialization.jsonObject(with: stringData, options : .allowFragments) [returns nil]
let data: Data? = try? JSONSerialization.data(withJSONObject: jsonArray as Any, options: .prettyPrinted)
Currently, the code breaks on the second to last line (starting with let jsonArray) and returns nil. Note that if I were to change code to "112345", there would be no error. Any help is appreciated, thanks!
Instead of manually creating string, use Dictionary and JSONSerialization to create data as below,
let code = "012345"
let body: [String: Any] = ["code": code]
do {
let stringData = try JSONSerialization.data(withJSONObject: body, options: .sortedKeys)
print(String.init(data: stringData, encoding: .utf8)!)
} catch {
print(error)
}
Output
{"code":"012345"}
I want to extract JSON string from html document "without" using third party Framework.
I'm trying to create iOS framework and I do not want to use third party Framework in it.
Example url:
http://www.nicovideo.jp/watch/sm33786214
In that html, there is a line:
I need to extract:
JSON_String_I_want_to extract
and convert it to JSON object.
With third party framework "Kanna", it is like this:
if let doc = Kanna.HTML(html: html, encoding: String.Encoding.utf8) {
if let descNode = doc.css("#js-initial-watch-data[data-api-data]").first {
let dataApiData = descNode["data-api-data"]
if let data = dataApiData?.data(using: .utf8) {
if let json = try? JSON(data: data, options: JSONSerialization.ReadingOptions.mutableContainers) {
I searched the web with similar question but unable to apply to my case:(I need to admit I'm not quite following regular expression)
if let html = String(data:data, encoding:.utf8) {
let pattern = "data-api-data=\"(.*?)\".*?>"
let regex = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let matches = regex.matches(in: html, options: [], range: NSMakeRange(0, html.count))
var results: [String] = []
matches.forEach { (match) -> () in
results.append( (html as NSString).substring(with: match.rangeAt(1)) )
}
if let stringJSON = results.first {
let d = stringJSON.data(using: String.Encoding.utf8)
if let json = try? JSONSerialization.jsonObject(with: d!, options: []) as? Any {
// it does not get here...
}
Anyone expert in extracting from html and convert it to JSON?
Thank you.
Your pattern does not seem to be bad, just that attribute values of HTML Elements may be using character entities.
You need to replace them into actual characters before parsing the String as JSON.
if let html = String(data:data, encoding: .utf8) {
let pattern = "data-api-data=\"([^\"]*)\""
let regex = try! NSRegularExpression(pattern: pattern, options: .caseInsensitive)
let matches = regex.matches(in: html, range: NSRange(0..<html.utf16.count)) //<-USE html.utf16.count, NOT html.count
var results: [String] = []
matches.forEach {match in
let propValue = html[Range(match.range(at: 1), in: html)!]
//### You need to replace character entities into actual characters
.replacingOccurrences(of: """, with: "\"")
.replacingOccurrences(of: "'", with: "'")
.replacingOccurrences(of: ">", with: ">")
.replacingOccurrences(of: "<", with: "<")
.replacingOccurrences(of: "&", with: "&")
results.append(propValue)
}
if let stringJSON = results.first {
let dataJSON = stringJSON.data(using: .utf8)!
do {
let json = try JSONSerialization.jsonObject(with: dataJSON)
print(json)
} catch {
print(error) //You should not ignore errors silently...
}
} else {
print("NO result")
}
}
I am trying to convert a dictionary to json string without space and new line. I tried to use JSONSerialization.jsonObject but I still can see spaces and new lines. Is there any way to have a string result looks something like this
"data": "{\"requests\":[{\"image\":{\"source\":{\"imageUri\":\"https://www.google.com/images/branding/googlelogo/2x/googlelogo_color_272x92dp.png\"}},\"features\":[{\"type\":\"LOGO_DETECTION\",\"maxResults\":1}]}]}"
My conversion
var features = [[String: String]]()
for detection in detections {
features.append(["type": imageDetection[detection]!])
}
let content = ["content": base64Image]
let request = ["image": content, "features": features] as [String : Any]
let requests = ["requests": [request]]
let jsonData = try! JSONSerialization.data(withJSONObject: requests, options: .prettyPrinted)
let decoded = try! JSONSerialization.jsonObject(with: jsonData, options: [])
print(decoded)
Result
{
requests = (
{
features = (
{
type = "LABEL_DETECTION";
},
{
type = "WEB_DETECTION";
},
{
type = "TEXT_DETECTION";
}
);
image = {
content = "iVBO
...........
You are decoding the serialized JSON into an object. When an object is printed into the console, you will see the indentation, and the use of equals symbols and parentheses.
Remove the .prettyPrinted option and use the data to initialize a string with .utf8 encoding.
let jsonData = try! JSONSerialization.data(withJSONObject: requests, options: [])
let decoded = String(data: jsonData!, encoding: .utf8)!
I am trying to display some JSON data on my iOS app but I am having an issue with displaying it correctly using Swift.
When I use the normal JSONSerializer for \u00c3\u00a9 i get é but I want to display é. I don't understand if it is an issue with say using UTF-16 rather than UTF-8 or something else?
Does anyone have any suggestions how I would convert \u00c3\u00a9 straight to é in Swift, from a JSON received from an API.
Not sure which encoding you're using, but this code works for both .utf8 and .utf16:
let jsonString = "{\"foo\": \"áéíóú\"}"
let data = jsonString.data(using: .utf16)!
do {
let object = try JSONSerialization.jsonObject(with: data, options: [])
if let dict = object as? [AnyHashable: Any], let text = dict["foo"] as? String {
print("Extracted text: \(text)")
}
}
catch let e {
// TODO: Handle error
print("Error processing JSON: \(e)")
}
was the same problem. Necessary use this code, it works:
Alamofire.request(url, method: .get, parameters: params)
.responseJSON{ response in
guard let data = response.data else {return}
do {
let jsonResult = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! NSDictionary
let json = jsonResult["response_goods"] as! [[String:String]]
print(json) } catch let err as NSError {print(err)
}
}