2017-09-05 3 views
-2

J'ai une donnée JSON avec structure et je ne sais pas comment utiliser la boucle for avec SwiftyJSON pour obtenir les entrées de chaque section de la valeur "path" et "updated". Quelqu'un peut-il aider? Merci.Comment faire une boucle sur les données JSON dans SwiftyJSON

var jsonData = "{ 
     "css":[ 
     { 
      "path": "style.css", 
      "updated": "12432" 
     }, 
     { 
      "path": "base.css", 
      "updated": "34627" 
     }, 

     ], 
     "html":[ 
     { 
      "path": "home.htm", 
      "updated": "3223" 
     }, 
     { 
      "path": "about", 
      "updated": "3987" 
     } 
     ] 
    } 
" 

J'ai essayé de coder une partie de boucle for

let json = JSON(jsonData) 

for () in json { 
    let filepath = 
    let updated = 

    // do searching another json to found file exists and updates 
} 

Répondre

2

Il est sur le README, sous la section intitulée "boucle": https://github.com/SwiftyJSON/SwiftyJSON#loop

// If json is .Dictionary 
for (key,subJson):(String, JSON) in json { 
    //Do something you want 
} 

// If json is .Array 
// The `index` is 0..<json.count's string value 
for (index,subJson):(String, JSON) in json { 
    //Do something you want 
} 

appliquée à votre spécifique Structure JSON:

let jsonData = """ 
    { 
     "css": [ 
     { 
      "path": "style.css", 
      "updated": "12432" 
     }, 
     { 
      "path": "base.css", 
      "updated": "34627" 
     } 
     ], 
     "html": [ 
     { 
      "path": "home.htm", 
      "updated": "3223" 
     }, 
     { 
      "path": "about", 
      "updated": "3987" 
     } 
     ] 
    } 
    """.data(using: .utf8)! 

    let json = JSON(data: jsonData) 

    for (_, subJson):(String, JSON) in json { 

     for (_, subJson):(String, JSON) in subJson { 
      let filepath = subJson["path"].stringValue 
      let updated = subJson["updated"].stringValue 

      print(filepath + " ~ " + updated) 
     } 
    } 

utilisant Swift 4 codable:

struct FileInfo: Decodable { 
    let path, updated: String 
} 

let dec = try! JSONDecoder().decode([String:[FileInfo]].self,from: jsonData) 
print(dec) 
0

Selon votre structure JSON, utilisez ceci:

for (index,subJson):(String, JSON) in json { 
    print(index) // this prints "css" , "html" 
    for (key,subJson):(String, JSON) in subJson { 
     let filepath = subJson["path"] 
     let updated = subJson["updated"] 
    } 
}