Reputation: 6505
I am trying to strip out unwanted slashes from a json file. I can't simply replace all instances of \ but rather, i need to escape instances of \" with just "
e.g. my json string looks like so:
[{
"type": "test",
"action": "test",
"filename": 1,
"data": "{\"a\":1,\"b\":10000,\"c\":0,\"d\":\"\"}"
}, {
"type": "test2",
"action": "test2",
"filename": 2,
"data": "{\"a\":2,\"b\":10000,\"c\":15,\"d\":\"\"}"
}]
I can't figure out the syntax of a find and replace for this:
let jsonStringTrimmed = jsonString.replacingOccurrences(of: "\"", with: """)
Another possible pitfall is that the param d is a base64 encoded string so I need to be able to avoid replacing \" within the value for that key
The goal is to be able to use jsonStringTrimmed as below:
let jsonStr = try String(contentsOf: path, encoding: String.Encoding.utf8)
let jsonStringTrimmed = jsonStr.replacingOccurrences(of: "\", with: """)
let json = try JSONSerializer.toDictionary(jsonStringTrimmed)
UPDATE:
I initially had tried:
do {
let jsonStr = try String(contentsOf: path, encoding: String.Encoding.utf8)
let json = try JSONSerializer.toDictionary(jsonStr)
}
catch {
print("Error reading file : \(error)")
}
And I was getting into the catch and receiving the error jsonIsNotDictinary
UPDATE 2 : Trying to loop through array after employing NivraD's approach:
if let jsonData = try? Data(contentsOf: path){
if let array = (try? JSONSerialization.jsonObject(with: jsonData, options: [])) as? [[String: Any]] {
for i in array{
print(array[i]?["data"] as! String)
let dataJsonStr = array[i]?["data"] as! String
if let dataDict = try? JSONSerializer.toDictionary(dataJsonStr){
print("a : \(dataDict["a"] as! String)")
}
}
}
else{
print("in the else of if let array")
}
}
else{
print("in the else of if let jsonData")
}
but this gives me the error: Cannot subscript value of type [[String : Any]] with an index of type Dictionary pointing to: print(employeeArray[i]?["data"] as! String)
Upvotes: 0
Views: 1177
Reputation: 72410
Your String is JSON
Array, so simply convert it to Array
no need to replacing anything with it. So first get Data
from jsonString
and then use this data
with JSONSerialization
to get Array
from it.
if let jsonData = try? Data(contentsOf: URL(fileURLWithPath: path))
if let array = (try? JSONSerialization.jsonObject(with: jsonData, options: [])) as? [[String: Any]] {
print(array.first?["a"])
}
}
Upvotes: 2