Tarvo Mäesepp
Tarvo Mäesepp

Reputation: 4533

Perfect JSON structure

I've been looking around and learning JSON a little bit. I thought it would be good to start learning with something easy but it seems it is not. I am trying to do JSON database. For example it has brand names and every brand has its own products with some info. I've done that like this which is actually much longer:

{
  "Snuses": {
    "Brands": {
      "CATCH": [
        {
          "Products": "CATCH EUCALYPTUS WHITE LARGE",
          "nicotine": "8.0"
        }
      ]
}

Now I am using Firebase to parse the "Brands" like "CATCH" etc.. But I can't.

In swift I am trying to do it like this:

override func viewDidLoad() {
    super.viewDidLoad()
    ref = FIRDatabase.database().reference()
    ref.observeSingleEventOfType(.Value, withBlock: { snapshot in

        self.ref = FIRDatabase.database().reference().child("Snuses").child("Brands")

        self.ref.observeEventType(.Value, withBlock: { snapshot -> Void in
            for brands in snapshot.children {
                print(brands)
            }
        })

    })
}

How to get reference to the Brands first? And how to store list of brands separately?

Some smart guys told me that it is not correct to do but I don't know what is wrong with the JSON structure. How can I flatten it?

I red the docs also that says how it is best to do it but it is a little to complicaetd. Can you point me to the right direction?

Upvotes: 0

Views: 103

Answers (1)

Bhavin Bhadani
Bhavin Bhadani

Reputation: 22374

You just need to do allKeys to get allKeys from snap

   let ref = FIRDatabase.database().reference().child("Snuses").child("Brands")

    ref.observeSingleEventOfType(.Value, withBlock: { (snapshot) in
        if snapshot.exists() {
            if let allProducts = (snapshot.value?.allKeys)! as? [String]{
                self.snusBrandsArray = allProducts                      
                self.productstable.reloadData()
            }
        }
    })

Upvotes: 1

Related Questions