uDevs
uDevs

Reputation: 29

Fetch value of dictionary from JSON

I want to fetch values of string from JSON , I am able to parse JSON to Dictionary but not able to convert into array of string

FROM SERVER

    {
        “ALL TEXT: [

  { 
    "text": "hello"
   },
   {
    "text": "hi"
   },
    {
    "text": "how r u"
    }
]
  }

I only want value of text to append to my string array "textsList"

    var textsList : [String]()

This is what I had tried

            URLSession.shared.dataTask(with: request) { (data, response, err) in                               
                   let json = try! JSONSerialization.jsonObject(with: data!, options: .allowFragments) as! Dictionary<String, Any>
                   
             
                let AllText = json[“ALL TEXT”] as!  [Dictionary<String, Any>]
                let value = JSON(AllText)
                
                AllText.forEach { fetch in
                  self.textsList.append(fetch.values) // ERROR no exact matches in call to instance method append
                                    }

           for(key, object) in value{
           print(value)  //output:  {"text": "hello" },{"text": "hi" }
           print(value.string)  //output:nil
            }

    
                   
               }.resume()

I just want to convert dictionary into array , but also alternate solution to convert JSON directly into array of string will be fine.

Upvotes: 2

Views: 103

Answers (1)

Alexander
Alexander

Reputation: 101

Adjust the code:

    let string = """
        {
            "ALL TEXT": [
          {
            "text": "hello"
           },
           {
            "text": "hi"
           },
            {
            "text": "how r u"
            }
        ]
      }
  """
    
    guard let data = string.data(using: .utf8),
    let json = try? JSONSerialization.jsonObject(with: data, options: []) as? Dictionary<String, Any>,
    let allText = json["ALL TEXT"] as? [Dictionary<String, Any>]
        else {
        DDLog("json fail")
        return }
    DDLog(allText) // [["text": hello], ["text": hi], ["text": how r u]]
    
    let items: [String] = allText.compactMap { $0["text"] as? String }
    
    var textsList = [String]()
    textsList.append(contentsOf: items)

    DDLog(items) //["hello", "hi", "how r u"]
    DDLog(textsList) //["hello", "hi", "how r u"]

Two errors:

1. <"ALL TEXT> Missing right quote;
2. var textsList: [String]() =》var textsList = [String]();

Upvotes: 2

Related Questions