简体   繁体   中英

I am trying to extract data from a json file and write that data into variables

I have a json file which I added to my project. The file contains 20 sets of data. The keys for this data are "Code", "Name", "Date", "Main", "Sup" and the data associated with these keys is of type String.

I have read the data to a local variable myData and then verified that the data is present by using a print statement to printed the contents of myData .

I want to extract the data from myData using the keys "Date" and "Main" and combine it into another String variable and I want to be able to do this for each of the 20 data sets.

I have tried using myData.Date & myData.Main , but the compiler complains and calls me an idiot. I am thinking that I should write the contents of myData to an array or dictionary but have been unable to do that, after days of searching the internet for a solution it's time to ask for some help.

myData contains data in the following form:

[{
    "Code" : "ABC"
    "Name" : "Fred"
    "Date" : "01/10/2019 13:00"
    "Main" : "1,2,3,4,5,6"
    "Sup"  : "Nil"
},
{
    "Code" : "DEF"
    "Name" : "Pete"
    "Date" : "03/10/2019 11:00"
    "Main" : "7,8,9,10,11,12"
    "Sup"  : "Nil"
}]

I verified that the json data was present by using:

let myData=readJFile(myJasonData)//this puts the json data into myData

print(myData)//this prints the contents of myData to console

I have created a data struct

struct  JsonData: Codable
{
    var code : String
    var Name : String
    var Date : String
    var Main : String
    var Sup  : String

}//struct lotData

and ensured that the keys in the json file match

let myDecoder = JSONDecoder()
let arrayDict = try myDecoder.decode(JsonData.self, from: myData)

print(arrayDict.Date)
print(arrayDict.Main)

The expected result is

variable1 = "01/10/2019 13:00,1,2,3,4,5,6"

variable2 = "03/10/2019 11:00,7,8,9,10,11,12"

many thanks in anticipation.

Please catch and print Decoding errors. They tell you exactly what's wrong.

The JSON is clearly an array. Please note the []

let result = try myDecoder.decode([JsonData].self, from: myData)
for item in result {
   print(item.Date, item.Main)
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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