swift json parsing, no titles for json objects Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) Data science time! April 2019 and salary with experience The Ask Question Wizard is Live! Should we burninate the [wrap] tag?How to call Objective-C code from Swift@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?Swift Beta performance: sorting arraysParsing JSON using Decodable and CodingKeys in Swift 4How to parse jsondata using API in swift 4How to parse particular JSON in SwiftHow to create a struct for this json data in swift4?Getting Nil trying to decode json

Extract all GPU name, model and GPU ram

Storing hydrofluoric acid before the invention of plastics

How would the world control an invulnerable immortal mass murderer?

List of Python versions

Why do we bend a book to keep it straight?

2001: A Space Odyssey's use of the song "Daisy Bell" (Bicycle Built for Two); life imitates art or vice-versa?

What is the meaning of the new sigil in Game of Thrones Season 8 intro?

Can a non-EU citizen traveling with me come with me through the EU passport line?

What exactly is a "Meth" in Altered Carbon?

How does the particle を relate to the verb 行く in the structure「A を + B に行く」?

How to find out what spells would be useless to a blind NPC spellcaster?

Single word antonym of "flightless"

Denied boarding although I have proper visa and documentation. To whom should I make a complaint?

Why are there no cargo aircraft with "flying wing" design?

How to deal with a team lead who never gives me credit?

What LEGO pieces have "real-world" functionality?

Book where humans were engineered with genes from animal species to survive hostile planets

How to react to hostile behavior from a senior developer?

Is there a program I can run on the C64 to speed up booting of a game?

How come Sam didn't become Lord of Horn Hill?

3 doors, three guards, one stone

Dating a Former Employee

Is it true that "carbohydrates are of no use for the basal metabolic need"?

What does this icon in iOS Stardew Valley mean?



swift json parsing, no titles for json objects



Announcing the arrival of Valued Associate #679: Cesar Manara
Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern)
Data science time! April 2019 and salary with experience
The Ask Question Wizard is Live!
Should we burninate the [wrap] tag?How to call Objective-C code from Swift@selector() in Swift?#pragma mark in Swift?Swift for loop: for index, element in array?Swift Beta performance: sorting arraysParsing JSON using Decodable and CodingKeys in Swift 4How to parse jsondata using API in swift 4How to parse particular JSON in SwiftHow to create a struct for this json data in swift4?Getting Nil trying to decode json



.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








-3















So I got a pretty hard problem to tackle. My JSON code has a pretty weird structure. It has the following structure:




"title": [
[
"Temperature",
"9 u00b0C (283 u00b0F)",
"Good"
],
[
"Visibility",
"10 KM (6.2 Mi)",
"Good"
]
]



With the following code I was able to print out some easy json code:



import UIKit

struct WeatherItem: Decodable
let title: String?
let value: String?
let condition: String?


class ViewController: UIViewController
override func viewDidLoad()
super.viewDidLoad()

let jsonUrlString = "http://somelinkhere"
guard let url = URL(string: jsonUrlString) else return

URLSession.shared.dataTask(with: url) (data, response, err) in
guard let data = data else return

do
let weather = try JSONDecoder().decode(WeatherItem.self, from: data)
print(weather.title)
catch let jsonErr
print("error", jsonErr)

.resume()




But the problem is that my output for all 3 variables, title, value and condition nil is.
I am sure I have to change the struct code, but I don't know in what way.



How do I get to JSON code with no title?










share|improve this question



















  • 1





    The JSON example you provided seems a bit off. I copied and paste it on jsonformatter.curiousconcept.com & it says its not valid. So if you can provide JSON that is valid, it would help.

    – Luis F Ramirez
    Mar 8 at 17:33











  • @LuisFRamirez the json is correct, it's just missing and

    – excitedmicrobe
    Mar 8 at 17:34






  • 1





    Ah, okay. Guess it was missing the brackets.

    – Luis F Ramirez
    Mar 8 at 17:47











  • hey thanks for your help! I tried your solution, but it didn't print anything

    – Dylan Strijker
    Mar 10 at 17:13











  • full json here: virtualflight.ddns.net/api/weather.php?icao=ehrd

    – Dylan Strijker
    Mar 10 at 17:13

















-3















So I got a pretty hard problem to tackle. My JSON code has a pretty weird structure. It has the following structure:




"title": [
[
"Temperature",
"9 u00b0C (283 u00b0F)",
"Good"
],
[
"Visibility",
"10 KM (6.2 Mi)",
"Good"
]
]



With the following code I was able to print out some easy json code:



import UIKit

struct WeatherItem: Decodable
let title: String?
let value: String?
let condition: String?


class ViewController: UIViewController
override func viewDidLoad()
super.viewDidLoad()

let jsonUrlString = "http://somelinkhere"
guard let url = URL(string: jsonUrlString) else return

URLSession.shared.dataTask(with: url) (data, response, err) in
guard let data = data else return

do
let weather = try JSONDecoder().decode(WeatherItem.self, from: data)
print(weather.title)
catch let jsonErr
print("error", jsonErr)

.resume()




But the problem is that my output for all 3 variables, title, value and condition nil is.
I am sure I have to change the struct code, but I don't know in what way.



How do I get to JSON code with no title?










share|improve this question



















  • 1





    The JSON example you provided seems a bit off. I copied and paste it on jsonformatter.curiousconcept.com & it says its not valid. So if you can provide JSON that is valid, it would help.

    – Luis F Ramirez
    Mar 8 at 17:33











  • @LuisFRamirez the json is correct, it's just missing and

    – excitedmicrobe
    Mar 8 at 17:34






  • 1





    Ah, okay. Guess it was missing the brackets.

    – Luis F Ramirez
    Mar 8 at 17:47











  • hey thanks for your help! I tried your solution, but it didn't print anything

    – Dylan Strijker
    Mar 10 at 17:13











  • full json here: virtualflight.ddns.net/api/weather.php?icao=ehrd

    – Dylan Strijker
    Mar 10 at 17:13













-3












-3








-3








So I got a pretty hard problem to tackle. My JSON code has a pretty weird structure. It has the following structure:




"title": [
[
"Temperature",
"9 u00b0C (283 u00b0F)",
"Good"
],
[
"Visibility",
"10 KM (6.2 Mi)",
"Good"
]
]



With the following code I was able to print out some easy json code:



import UIKit

struct WeatherItem: Decodable
let title: String?
let value: String?
let condition: String?


class ViewController: UIViewController
override func viewDidLoad()
super.viewDidLoad()

let jsonUrlString = "http://somelinkhere"
guard let url = URL(string: jsonUrlString) else return

URLSession.shared.dataTask(with: url) (data, response, err) in
guard let data = data else return

do
let weather = try JSONDecoder().decode(WeatherItem.self, from: data)
print(weather.title)
catch let jsonErr
print("error", jsonErr)

.resume()




But the problem is that my output for all 3 variables, title, value and condition nil is.
I am sure I have to change the struct code, but I don't know in what way.



How do I get to JSON code with no title?










share|improve this question
















So I got a pretty hard problem to tackle. My JSON code has a pretty weird structure. It has the following structure:




"title": [
[
"Temperature",
"9 u00b0C (283 u00b0F)",
"Good"
],
[
"Visibility",
"10 KM (6.2 Mi)",
"Good"
]
]



With the following code I was able to print out some easy json code:



import UIKit

struct WeatherItem: Decodable
let title: String?
let value: String?
let condition: String?


class ViewController: UIViewController
override func viewDidLoad()
super.viewDidLoad()

let jsonUrlString = "http://somelinkhere"
guard let url = URL(string: jsonUrlString) else return

URLSession.shared.dataTask(with: url) (data, response, err) in
guard let data = data else return

do
let weather = try JSONDecoder().decode(WeatherItem.self, from: data)
print(weather.title)
catch let jsonErr
print("error", jsonErr)

.resume()




But the problem is that my output for all 3 variables, title, value and condition nil is.
I am sure I have to change the struct code, but I don't know in what way.



How do I get to JSON code with no title?







swift codable






share|improve this question















share|improve this question













share|improve this question




share|improve this question








edited Mar 8 at 19:23









excitedmicrobe

1,1231519




1,1231519










asked Mar 8 at 17:22









Dylan StrijkerDylan Strijker

55




55







  • 1





    The JSON example you provided seems a bit off. I copied and paste it on jsonformatter.curiousconcept.com & it says its not valid. So if you can provide JSON that is valid, it would help.

    – Luis F Ramirez
    Mar 8 at 17:33











  • @LuisFRamirez the json is correct, it's just missing and

    – excitedmicrobe
    Mar 8 at 17:34






  • 1





    Ah, okay. Guess it was missing the brackets.

    – Luis F Ramirez
    Mar 8 at 17:47











  • hey thanks for your help! I tried your solution, but it didn't print anything

    – Dylan Strijker
    Mar 10 at 17:13











  • full json here: virtualflight.ddns.net/api/weather.php?icao=ehrd

    – Dylan Strijker
    Mar 10 at 17:13












  • 1





    The JSON example you provided seems a bit off. I copied and paste it on jsonformatter.curiousconcept.com & it says its not valid. So if you can provide JSON that is valid, it would help.

    – Luis F Ramirez
    Mar 8 at 17:33











  • @LuisFRamirez the json is correct, it's just missing and

    – excitedmicrobe
    Mar 8 at 17:34






  • 1





    Ah, okay. Guess it was missing the brackets.

    – Luis F Ramirez
    Mar 8 at 17:47











  • hey thanks for your help! I tried your solution, but it didn't print anything

    – Dylan Strijker
    Mar 10 at 17:13











  • full json here: virtualflight.ddns.net/api/weather.php?icao=ehrd

    – Dylan Strijker
    Mar 10 at 17:13







1




1





The JSON example you provided seems a bit off. I copied and paste it on jsonformatter.curiousconcept.com & it says its not valid. So if you can provide JSON that is valid, it would help.

– Luis F Ramirez
Mar 8 at 17:33





The JSON example you provided seems a bit off. I copied and paste it on jsonformatter.curiousconcept.com & it says its not valid. So if you can provide JSON that is valid, it would help.

– Luis F Ramirez
Mar 8 at 17:33













@LuisFRamirez the json is correct, it's just missing and

– excitedmicrobe
Mar 8 at 17:34





@LuisFRamirez the json is correct, it's just missing and

– excitedmicrobe
Mar 8 at 17:34




1




1





Ah, okay. Guess it was missing the brackets.

– Luis F Ramirez
Mar 8 at 17:47





Ah, okay. Guess it was missing the brackets.

– Luis F Ramirez
Mar 8 at 17:47













hey thanks for your help! I tried your solution, but it didn't print anything

– Dylan Strijker
Mar 10 at 17:13





hey thanks for your help! I tried your solution, but it didn't print anything

– Dylan Strijker
Mar 10 at 17:13













full json here: virtualflight.ddns.net/api/weather.php?icao=ehrd

– Dylan Strijker
Mar 10 at 17:13





full json here: virtualflight.ddns.net/api/weather.php?icao=ehrd

– Dylan Strijker
Mar 10 at 17:13












3 Answers
3






active

oldest

votes


















1














You will have to write the decoding initializer by yourself:



struct WeatherData: Decodable 
let title: [WeatherItem]


struct WeatherItem: Decodable
let title: String?
let value: String?
let condition: String?

public init(from decoder: Decoder) throws
// decode the value for WeatherItem as [String]
let container = try decoder.singleValueContainer()
let components = try container.decode([String].self)

title = components.count > 0 ? components[0] : nil
value = components.count > 1 ? components[1] : nil
condition = components.count > 2 ? components[2] : nil



let json = """

"title": [
["Temperature", "9", "Good"],
["Visibility", "10 KM (6.2 Mi)", "Good"]
]

"""

let jsonData: Data = json.data(using: .utf8)!
let decoder = JSONDecoder()

let decoded = try! decoder.decode(WeatherData.self, from: jsonData)
debugPrint(decoded)





share|improve this answer























  • but the JSON info is always changing.

    – Dylan Strijker
    Mar 8 at 17:55











  • @DylanStrijker The structure changes? You haven't specified that in your question! That it would be probably better for WeatherItem to just hold [String]? It's unclear what is the format of the data and what operations you are doing on them.

    – Sulthan
    Mar 8 at 17:59











  • I meant the info always changes. Like, the word temperaturen will be the same, but the second string will chnage.

    – Dylan Strijker
    Mar 9 at 20:57











  • @DylanStrijker I don't see the problem then. I have just used that JSON as an example how to parse the data. I thought that would be obvious.

    – Sulthan
    Mar 9 at 21:28












  • okay thanks! Your example works, but I would like to use this link: virtualflight.ddns.net/api/weather.php?icao=ehrd how can I do it with a link? I am beginner with JSON parsing

    – Dylan Strijker
    Mar 10 at 16:51


















1














Correct json




"title": [
[
"Temperature",
" ",
"Good"
],
[
"Visibility",
"10 KM (6.2 Mi)",
"Good"
]
]





var arr = [WeatherItem]()
do
let res = try JSONDecoder().decode([String:[[String]]].self, from: data)
let content = res["title"]!
content.forEach
if $0.count >= 3
arr.append(WeatherItem(title:$0[0],value:$0[1],condition:$0[2]))


print(arr)
catch
print(error)



Discussion : your root object is a dictionary that contains 1 key named title and it's value is an array of array of strings or from the model logic it's an array of model named WeatherItem but isn't structured properly for it , so using this



let weather = try JSONDecoder().decode(WeatherItem.self, from: data)


won't work as the current json does't contain keys value and condition



A proper strcuture would be



[

"title":"Temperature" ,
"value":"",
"condition":"Good"
,

"title":"Visibility",
"title":"10 KM (6.2 Mi)",
"condition":"Good"

]


and that will enable you to do



let weather = try JSONDecoder().decode([WeatherItem].self, from: data)





share|improve this answer
































    0














    To decode an array using Decoder() in swift. you do something like this:



    let decoder = JSONDecoder()
    do
    let array = try decoder.decode([WeatherItem].self, from: data)
    print(array)
    catch
    // handle errors






    share|improve this answer























      Your Answer






      StackExchange.ifUsing("editor", function ()
      StackExchange.using("externalEditor", function ()
      StackExchange.using("snippets", function ()
      StackExchange.snippets.init();
      );
      );
      , "code-snippets");

      StackExchange.ready(function()
      var channelOptions =
      tags: "".split(" "),
      id: "1"
      ;
      initTagRenderer("".split(" "), "".split(" "), channelOptions);

      StackExchange.using("externalEditor", function()
      // Have to fire editor after snippets, if snippets enabled
      if (StackExchange.settings.snippets.snippetsEnabled)
      StackExchange.using("snippets", function()
      createEditor();
      );

      else
      createEditor();

      );

      function createEditor()
      StackExchange.prepareEditor(
      heartbeatType: 'answer',
      autoActivateHeartbeat: false,
      convertImagesToLinks: true,
      noModals: true,
      showLowRepImageUploadWarning: true,
      reputationToPostImages: 10,
      bindNavPrevention: true,
      postfix: "",
      imageUploader:
      brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
      contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
      allowUrls: true
      ,
      onDemand: true,
      discardSelector: ".discard-answer"
      ,immediatelyShowMarkdownHelp:true
      );



      );













      draft saved

      draft discarded


















      StackExchange.ready(
      function ()
      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55068090%2fswift-json-parsing-no-titles-for-json-objects%23new-answer', 'question_page');

      );

      Post as a guest















      Required, but never shown

























      3 Answers
      3






      active

      oldest

      votes








      3 Answers
      3






      active

      oldest

      votes









      active

      oldest

      votes






      active

      oldest

      votes









      1














      You will have to write the decoding initializer by yourself:



      struct WeatherData: Decodable 
      let title: [WeatherItem]


      struct WeatherItem: Decodable
      let title: String?
      let value: String?
      let condition: String?

      public init(from decoder: Decoder) throws
      // decode the value for WeatherItem as [String]
      let container = try decoder.singleValueContainer()
      let components = try container.decode([String].self)

      title = components.count > 0 ? components[0] : nil
      value = components.count > 1 ? components[1] : nil
      condition = components.count > 2 ? components[2] : nil



      let json = """

      "title": [
      ["Temperature", "9", "Good"],
      ["Visibility", "10 KM (6.2 Mi)", "Good"]
      ]

      """

      let jsonData: Data = json.data(using: .utf8)!
      let decoder = JSONDecoder()

      let decoded = try! decoder.decode(WeatherData.self, from: jsonData)
      debugPrint(decoded)





      share|improve this answer























      • but the JSON info is always changing.

        – Dylan Strijker
        Mar 8 at 17:55











      • @DylanStrijker The structure changes? You haven't specified that in your question! That it would be probably better for WeatherItem to just hold [String]? It's unclear what is the format of the data and what operations you are doing on them.

        – Sulthan
        Mar 8 at 17:59











      • I meant the info always changes. Like, the word temperaturen will be the same, but the second string will chnage.

        – Dylan Strijker
        Mar 9 at 20:57











      • @DylanStrijker I don't see the problem then. I have just used that JSON as an example how to parse the data. I thought that would be obvious.

        – Sulthan
        Mar 9 at 21:28












      • okay thanks! Your example works, but I would like to use this link: virtualflight.ddns.net/api/weather.php?icao=ehrd how can I do it with a link? I am beginner with JSON parsing

        – Dylan Strijker
        Mar 10 at 16:51















      1














      You will have to write the decoding initializer by yourself:



      struct WeatherData: Decodable 
      let title: [WeatherItem]


      struct WeatherItem: Decodable
      let title: String?
      let value: String?
      let condition: String?

      public init(from decoder: Decoder) throws
      // decode the value for WeatherItem as [String]
      let container = try decoder.singleValueContainer()
      let components = try container.decode([String].self)

      title = components.count > 0 ? components[0] : nil
      value = components.count > 1 ? components[1] : nil
      condition = components.count > 2 ? components[2] : nil



      let json = """

      "title": [
      ["Temperature", "9", "Good"],
      ["Visibility", "10 KM (6.2 Mi)", "Good"]
      ]

      """

      let jsonData: Data = json.data(using: .utf8)!
      let decoder = JSONDecoder()

      let decoded = try! decoder.decode(WeatherData.self, from: jsonData)
      debugPrint(decoded)





      share|improve this answer























      • but the JSON info is always changing.

        – Dylan Strijker
        Mar 8 at 17:55











      • @DylanStrijker The structure changes? You haven't specified that in your question! That it would be probably better for WeatherItem to just hold [String]? It's unclear what is the format of the data and what operations you are doing on them.

        – Sulthan
        Mar 8 at 17:59











      • I meant the info always changes. Like, the word temperaturen will be the same, but the second string will chnage.

        – Dylan Strijker
        Mar 9 at 20:57











      • @DylanStrijker I don't see the problem then. I have just used that JSON as an example how to parse the data. I thought that would be obvious.

        – Sulthan
        Mar 9 at 21:28












      • okay thanks! Your example works, but I would like to use this link: virtualflight.ddns.net/api/weather.php?icao=ehrd how can I do it with a link? I am beginner with JSON parsing

        – Dylan Strijker
        Mar 10 at 16:51













      1












      1








      1







      You will have to write the decoding initializer by yourself:



      struct WeatherData: Decodable 
      let title: [WeatherItem]


      struct WeatherItem: Decodable
      let title: String?
      let value: String?
      let condition: String?

      public init(from decoder: Decoder) throws
      // decode the value for WeatherItem as [String]
      let container = try decoder.singleValueContainer()
      let components = try container.decode([String].self)

      title = components.count > 0 ? components[0] : nil
      value = components.count > 1 ? components[1] : nil
      condition = components.count > 2 ? components[2] : nil



      let json = """

      "title": [
      ["Temperature", "9", "Good"],
      ["Visibility", "10 KM (6.2 Mi)", "Good"]
      ]

      """

      let jsonData: Data = json.data(using: .utf8)!
      let decoder = JSONDecoder()

      let decoded = try! decoder.decode(WeatherData.self, from: jsonData)
      debugPrint(decoded)





      share|improve this answer













      You will have to write the decoding initializer by yourself:



      struct WeatherData: Decodable 
      let title: [WeatherItem]


      struct WeatherItem: Decodable
      let title: String?
      let value: String?
      let condition: String?

      public init(from decoder: Decoder) throws
      // decode the value for WeatherItem as [String]
      let container = try decoder.singleValueContainer()
      let components = try container.decode([String].self)

      title = components.count > 0 ? components[0] : nil
      value = components.count > 1 ? components[1] : nil
      condition = components.count > 2 ? components[2] : nil



      let json = """

      "title": [
      ["Temperature", "9", "Good"],
      ["Visibility", "10 KM (6.2 Mi)", "Good"]
      ]

      """

      let jsonData: Data = json.data(using: .utf8)!
      let decoder = JSONDecoder()

      let decoded = try! decoder.decode(WeatherData.self, from: jsonData)
      debugPrint(decoded)






      share|improve this answer












      share|improve this answer



      share|improve this answer










      answered Mar 8 at 17:46









      SulthanSulthan

      99.9k16162205




      99.9k16162205












      • but the JSON info is always changing.

        – Dylan Strijker
        Mar 8 at 17:55











      • @DylanStrijker The structure changes? You haven't specified that in your question! That it would be probably better for WeatherItem to just hold [String]? It's unclear what is the format of the data and what operations you are doing on them.

        – Sulthan
        Mar 8 at 17:59











      • I meant the info always changes. Like, the word temperaturen will be the same, but the second string will chnage.

        – Dylan Strijker
        Mar 9 at 20:57











      • @DylanStrijker I don't see the problem then. I have just used that JSON as an example how to parse the data. I thought that would be obvious.

        – Sulthan
        Mar 9 at 21:28












      • okay thanks! Your example works, but I would like to use this link: virtualflight.ddns.net/api/weather.php?icao=ehrd how can I do it with a link? I am beginner with JSON parsing

        – Dylan Strijker
        Mar 10 at 16:51

















      • but the JSON info is always changing.

        – Dylan Strijker
        Mar 8 at 17:55











      • @DylanStrijker The structure changes? You haven't specified that in your question! That it would be probably better for WeatherItem to just hold [String]? It's unclear what is the format of the data and what operations you are doing on them.

        – Sulthan
        Mar 8 at 17:59











      • I meant the info always changes. Like, the word temperaturen will be the same, but the second string will chnage.

        – Dylan Strijker
        Mar 9 at 20:57











      • @DylanStrijker I don't see the problem then. I have just used that JSON as an example how to parse the data. I thought that would be obvious.

        – Sulthan
        Mar 9 at 21:28












      • okay thanks! Your example works, but I would like to use this link: virtualflight.ddns.net/api/weather.php?icao=ehrd how can I do it with a link? I am beginner with JSON parsing

        – Dylan Strijker
        Mar 10 at 16:51
















      but the JSON info is always changing.

      – Dylan Strijker
      Mar 8 at 17:55





      but the JSON info is always changing.

      – Dylan Strijker
      Mar 8 at 17:55













      @DylanStrijker The structure changes? You haven't specified that in your question! That it would be probably better for WeatherItem to just hold [String]? It's unclear what is the format of the data and what operations you are doing on them.

      – Sulthan
      Mar 8 at 17:59





      @DylanStrijker The structure changes? You haven't specified that in your question! That it would be probably better for WeatherItem to just hold [String]? It's unclear what is the format of the data and what operations you are doing on them.

      – Sulthan
      Mar 8 at 17:59













      I meant the info always changes. Like, the word temperaturen will be the same, but the second string will chnage.

      – Dylan Strijker
      Mar 9 at 20:57





      I meant the info always changes. Like, the word temperaturen will be the same, but the second string will chnage.

      – Dylan Strijker
      Mar 9 at 20:57













      @DylanStrijker I don't see the problem then. I have just used that JSON as an example how to parse the data. I thought that would be obvious.

      – Sulthan
      Mar 9 at 21:28






      @DylanStrijker I don't see the problem then. I have just used that JSON as an example how to parse the data. I thought that would be obvious.

      – Sulthan
      Mar 9 at 21:28














      okay thanks! Your example works, but I would like to use this link: virtualflight.ddns.net/api/weather.php?icao=ehrd how can I do it with a link? I am beginner with JSON parsing

      – Dylan Strijker
      Mar 10 at 16:51





      okay thanks! Your example works, but I would like to use this link: virtualflight.ddns.net/api/weather.php?icao=ehrd how can I do it with a link? I am beginner with JSON parsing

      – Dylan Strijker
      Mar 10 at 16:51













      1














      Correct json




      "title": [
      [
      "Temperature",
      " ",
      "Good"
      ],
      [
      "Visibility",
      "10 KM (6.2 Mi)",
      "Good"
      ]
      ]





      var arr = [WeatherItem]()
      do
      let res = try JSONDecoder().decode([String:[[String]]].self, from: data)
      let content = res["title"]!
      content.forEach
      if $0.count >= 3
      arr.append(WeatherItem(title:$0[0],value:$0[1],condition:$0[2]))


      print(arr)
      catch
      print(error)



      Discussion : your root object is a dictionary that contains 1 key named title and it's value is an array of array of strings or from the model logic it's an array of model named WeatherItem but isn't structured properly for it , so using this



      let weather = try JSONDecoder().decode(WeatherItem.self, from: data)


      won't work as the current json does't contain keys value and condition



      A proper strcuture would be



      [

      "title":"Temperature" ,
      "value":"",
      "condition":"Good"
      ,

      "title":"Visibility",
      "title":"10 KM (6.2 Mi)",
      "condition":"Good"

      ]


      and that will enable you to do



      let weather = try JSONDecoder().decode([WeatherItem].self, from: data)





      share|improve this answer





























        1














        Correct json




        "title": [
        [
        "Temperature",
        " ",
        "Good"
        ],
        [
        "Visibility",
        "10 KM (6.2 Mi)",
        "Good"
        ]
        ]





        var arr = [WeatherItem]()
        do
        let res = try JSONDecoder().decode([String:[[String]]].self, from: data)
        let content = res["title"]!
        content.forEach
        if $0.count >= 3
        arr.append(WeatherItem(title:$0[0],value:$0[1],condition:$0[2]))


        print(arr)
        catch
        print(error)



        Discussion : your root object is a dictionary that contains 1 key named title and it's value is an array of array of strings or from the model logic it's an array of model named WeatherItem but isn't structured properly for it , so using this



        let weather = try JSONDecoder().decode(WeatherItem.self, from: data)


        won't work as the current json does't contain keys value and condition



        A proper strcuture would be



        [

        "title":"Temperature" ,
        "value":"",
        "condition":"Good"
        ,

        "title":"Visibility",
        "title":"10 KM (6.2 Mi)",
        "condition":"Good"

        ]


        and that will enable you to do



        let weather = try JSONDecoder().decode([WeatherItem].self, from: data)





        share|improve this answer



























          1












          1








          1







          Correct json




          "title": [
          [
          "Temperature",
          " ",
          "Good"
          ],
          [
          "Visibility",
          "10 KM (6.2 Mi)",
          "Good"
          ]
          ]





          var arr = [WeatherItem]()
          do
          let res = try JSONDecoder().decode([String:[[String]]].self, from: data)
          let content = res["title"]!
          content.forEach
          if $0.count >= 3
          arr.append(WeatherItem(title:$0[0],value:$0[1],condition:$0[2]))


          print(arr)
          catch
          print(error)



          Discussion : your root object is a dictionary that contains 1 key named title and it's value is an array of array of strings or from the model logic it's an array of model named WeatherItem but isn't structured properly for it , so using this



          let weather = try JSONDecoder().decode(WeatherItem.self, from: data)


          won't work as the current json does't contain keys value and condition



          A proper strcuture would be



          [

          "title":"Temperature" ,
          "value":"",
          "condition":"Good"
          ,

          "title":"Visibility",
          "title":"10 KM (6.2 Mi)",
          "condition":"Good"

          ]


          and that will enable you to do



          let weather = try JSONDecoder().decode([WeatherItem].self, from: data)





          share|improve this answer















          Correct json




          "title": [
          [
          "Temperature",
          " ",
          "Good"
          ],
          [
          "Visibility",
          "10 KM (6.2 Mi)",
          "Good"
          ]
          ]





          var arr = [WeatherItem]()
          do
          let res = try JSONDecoder().decode([String:[[String]]].self, from: data)
          let content = res["title"]!
          content.forEach
          if $0.count >= 3
          arr.append(WeatherItem(title:$0[0],value:$0[1],condition:$0[2]))


          print(arr)
          catch
          print(error)



          Discussion : your root object is a dictionary that contains 1 key named title and it's value is an array of array of strings or from the model logic it's an array of model named WeatherItem but isn't structured properly for it , so using this



          let weather = try JSONDecoder().decode(WeatherItem.self, from: data)


          won't work as the current json does't contain keys value and condition



          A proper strcuture would be



          [

          "title":"Temperature" ,
          "value":"",
          "condition":"Good"
          ,

          "title":"Visibility",
          "title":"10 KM (6.2 Mi)",
          "condition":"Good"

          ]


          and that will enable you to do



          let weather = try JSONDecoder().decode([WeatherItem].self, from: data)






          share|improve this answer














          share|improve this answer



          share|improve this answer








          edited Mar 8 at 18:06

























          answered Mar 8 at 17:40









          Sh_KhanSh_Khan

          48k51434




          48k51434





















              0














              To decode an array using Decoder() in swift. you do something like this:



              let decoder = JSONDecoder()
              do
              let array = try decoder.decode([WeatherItem].self, from: data)
              print(array)
              catch
              // handle errors






              share|improve this answer



























                0














                To decode an array using Decoder() in swift. you do something like this:



                let decoder = JSONDecoder()
                do
                let array = try decoder.decode([WeatherItem].self, from: data)
                print(array)
                catch
                // handle errors






                share|improve this answer

























                  0












                  0








                  0







                  To decode an array using Decoder() in swift. you do something like this:



                  let decoder = JSONDecoder()
                  do
                  let array = try decoder.decode([WeatherItem].self, from: data)
                  print(array)
                  catch
                  // handle errors






                  share|improve this answer













                  To decode an array using Decoder() in swift. you do something like this:



                  let decoder = JSONDecoder()
                  do
                  let array = try decoder.decode([WeatherItem].self, from: data)
                  print(array)
                  catch
                  // handle errors







                  share|improve this answer












                  share|improve this answer



                  share|improve this answer










                  answered Mar 8 at 17:32









                  excitedmicrobeexcitedmicrobe

                  1,1231519




                  1,1231519



























                      draft saved

                      draft discarded
















































                      Thanks for contributing an answer to Stack Overflow!


                      • Please be sure to answer the question. Provide details and share your research!

                      But avoid


                      • Asking for help, clarification, or responding to other answers.

                      • Making statements based on opinion; back them up with references or personal experience.

                      To learn more, see our tips on writing great answers.




                      draft saved


                      draft discarded














                      StackExchange.ready(
                      function ()
                      StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55068090%2fswift-json-parsing-no-titles-for-json-objects%23new-answer', 'question_page');

                      );

                      Post as a guest















                      Required, but never shown





















































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown

































                      Required, but never shown














                      Required, but never shown












                      Required, but never shown







                      Required, but never shown







                      Popular posts from this blog

                      AWS Lex not identifying response if by a variable The 2019 Stack Overflow Developer Survey Results Are In Announcing the arrival of Valued Associate #679: Cesar Manara Planned maintenance scheduled April 17/18, 2019 at 00:00UTC (8:00pm US/Eastern) The Ask Question Wizard is Live! Data science time! April 2019 and salary with experienceEnforcing custom enumeration in AWS LEX for slot valuesHow to give response based on user response in Amazon Lex?Intercepting AWS Lambda Response to a AWS Lex QueryLex chat bot error: Reached second execution of fulfillment lambda on the same utteranceamazon lex showing invalid responseLambda response send back to Lex slot?Response card in Amazon lexAmazon Lex - Lambda response return HTML to botHow can I solve 424 (Failed Dependency) (python) obtained from Amazon lex?

                      Алба-Юлія

                      Захаров Федір Захарович