0

I am trying to add json to existing JSON file. json is added to file but it removes the existing json data. I tried everything but its not working for me.

enter image description here

   let path = Bundle.main.path(forResource: "menu", ofType: "json")!
    print(path)
    ///geting existing json file
    let dataFromFile = try? Data(contentsOf: URL(fileURLWithPath: path))
    let jsonData = try! JSON(data: dataFromFile!)

    var data: [JSON] = []

    let dataDic =  ["name": "Biryani", "Price": "24", "menuType":"Mains","logo" : "mains1"]
    print(dataDic)
    var newitemjson = JSON(dataDic)
    data = [newitemjson]
    data = data + jsonData["Mains"].arrayValue
    print(data)
    let str = data.description
      let saveData = str.data(using: .utf8)!

     if let file = FileHandle(forWritingAtPath:path) {
          //  let rawData = try? JSONSerialization.data(withJSONObject: newitemjson, options: .prettyPrinted)
            file.write(saveData)
            }
theduck
  • 2,589
  • 13
  • 17
  • 23
  • 1
    Don't post images of code or data, post it as text instead. Besides that it looks to me like you are trying to write to the main bundle which isn't allowed. – Joakim Danielson Oct 25 '19 at 20:57
  • i was trying to add json syntax but its saying format is not correct because i don't know how to add json in stackoverflow, so i used image – Irfan Abdul khaliq Oct 25 '19 at 21:12
  • its is allowed but the issue is when i write data it replaces the with json file data and removes old data from json – Irfan Abdul khaliq Oct 25 '19 at 21:20
  • i want to append dictOBject to existing json object in json file – Irfan Abdul khaliq Oct 25 '19 at 21:21
  • [This answer](https://stackoverflow.com/a/27327385/11760652) might help. Note that simply appending would leave you with content in the [JSON Lines](http://jsonlines.org/) format. – iamtimmo Jan 15 '20 at 17:47

0 Answers0