Tarvo Mäesepp Tarvo Mäesepp - 4 months ago 18
Swift Question

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"
},
{
"Products": "CATCH DRY EUCALYPTUS WHITE MINI",
"nicotine": "15.0"
},
{
"Products": "CATCH LICORICE WHITE LARGE",
"nicotine": "8.0"
},
{
"Products": "CATCH DRY LICORICE WHITE MINI",
"nicotine": "15.0"
},
{
"Products": "CATCH LICORICE MINI",
"nicotine": "8.0"
},
{
"Products": "CATCH WHITE SPEARMINT MINI",
"nicotine": "8.0"
},
{
"Products": "XRANGE CATCH SLIM LARGE WHITE MINT",
"nicotine": "9.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?

Answer

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()
            }
        }
    })
Comments