简体   繁体   English

使用Swift将JSON或CSV数据导入到Firestore

[英]Importing JSON or CSV data to Firestore using Swift

It appears there is still no way to import JSON or CSV files directly to a Firestore database. 看来仍然无法直接将JSON或CSV文件导入Firestore数据库。 Many of the suggestions are for JavaScript-based apps that do not translate well to Swift. 许多建议是针对不能很好地转换为Swift的基于JavaScript的应用程序的。 Does anyone have a good Swift solution for adding data to a Firestore database using JSON/CSV? 有没有人有很好的Swift解决方案,可以使用JSON / CSV将数据添加到Firestore数据库中?

//example json
[
  {
    "name": "Stone Cove Marina Inc",
    "email": "NOT IN SAMPLE",
    "category": "Docks",
    "category2": "Marinas",
    "category3": "Dock Builders",
    "address": "134 Salt Pond Rd",
    "city": "Wakefield",
    "state": "RI",
    "zip": 2879,
    "phone": "(401) 783-8990",
    "website": "http://stonecovemarinari.com"
  },
  {
    "name": "Bluehaven Homes",
    "email": "NOT IN SAMPLE",
    "category": "General Contractors",
    "category2": "Home Builders",
    "category3": "",
    "address": "5701 Time Sq",
    "city": "Amarillo",
    "state": "TX",
    "zip": 79119,
    "phone": "(806) 452-2545",
    "website": "http://www.bluehavenhomes.com/"
  }
]

//here is the database structure
//collection is "businesses"; each "business" gets a document id; within each document id set the data

database.collection("businesses").document().setData(/*data here*/)

You can try 你可以试试

let str = """

      [
      {
        "name": "Stone Cove Marina Inc",
        "email": "NOT IN SAMPLE",
        "category": "Docks",
        "category2": "Marinas",
        "category3": "Dock Builders",
        "address": "134 Salt Pond Rd",
        "city": "Wakefield",
        "state": "RI",
        "zip": 2879,
        "phone": "(401) 783-8990",
        "website": "http://stonecovemarinari.com"
      },
      {
        "name": "Bluehaven Homes",
        "email": "NOT IN SAMPLE",
        "category": "General Contractors",
        "category2": "Home Builders",
        "category3": "",
        "address": "5701 Time Sq",
        "city": "Amarillo",
        "state": "TX",
        "zip": 79119,
        "phone": "(806) 452-2545",
        "website": "http://www.bluehavenhomes.com/"
      }
    ]

"""

do {
    let json = try JSONSerialization.jsonObject(with:str.data(using:.utf8)!, options: []) as! [[String: Any]]
    for var i in 0...json.count - 1
    {
      database.collection("businesses").document().setData(json[i])
    }
} catch  {
    print(error)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM