I have a local .json file and I want to read and write data to it. With reading, I have no problems:
let file = Bundle.main.url(forResource: "categories", withExtension: "json")
let data = try? Data(contentsOf: file)
let json = try? JSONSerialization.jsonObject(with: data, options: [])
But writing doesn't work. My code(jsonData
& file
not nil):
let dict = ["data": categories.compactMap { $0.dictionary }]
let file = Bundle.main.url(forResource: "categories", withExtension: "json")
let jsonData = try? JSONSerialization.data(withJSONObject: dict, options: [])
try? jsonData?.write(to: file!)
.json file inside looks like this:
{
"data" : [
{
"id" : "new",
"name" : "New"
}]
}