[Swift5] Get array (individual) information from JSON using library'SwiftyJSON'

What is Swifty JSON

A library for handling JSON easily. It can be implemented with simpler code by using a library when parsing JSON.

Please refer to the attached document. https://github.com/SwiftyJSON/SwiftyJSON

Posting points

This time, I don't think that the analysis will be performed with reference to the JSON obtained in the article ** [Swift5] Converting the analysis result obtained by "IBM Watson Tone Analyzer" to JSON ** posted last time. If you haven't seen the article last time, please read it first.

▼ Previous article https://qiita.com/nkekisasa222/items/3304cb77d78d9adfe8ac

Library installation

First, install the pod in the Podfile.

podfile.


# Uncomment the next line to define a global platform for your project
# platform :ios, '9.0'

target 'app name' do
  # Comment the next line if you don't want to use dynamic frameworks
  use_frameworks!

  #Pods for app name

pod 'SwiftyJSON'
end

Then run $ pod install in your terminal to import the` application's Swifty JSON into the Controller you want to use.

ViewController.swift


import UIKit
import SwiftyJSON //Describe here

Confirmation of the value to be acquired this time

In the previous article, I converted the analysis result to JSON format. The following is the content.

JSON.


JSON: {
  "sentences_tone" : [
    {
      "sentence_id" : 0,
      "text" : "Team, I know that times are tough!",
      "tones" : [
        {
          "score" : 0.80182699999999996,
          "tone_id" : "analytical",
          "tone_name" : "Analytical"
        }
      ]
    },
    {
      "sentence_id" : 1,
      "text" : "Product sales have been disappointing for the past three quarters.",
      "tones" : [
        {
          "score" : 0.77124099999999995,
          "tone_id" : "sadness",
          "tone_name" : "Sadness"
        },
        {
          "score" : 0.68776800000000005,
          "tone_id" : "analytical",
          "tone_name" : "Analytical"
        }
      ]
    },
    {
      "sentence_id" : 2,
      "text" : "We have a competitive product, but we need to do a better job of selling it!",
      "tones" : [
        {
          "score" : 0.50676299999999996,
          "tone_id" : "analytical",
          "tone_name" : "Analytical"
        }
      ]
    }
  ],
  "document_tone" : {
    "tones" : [
      {
        "score" : 0.61650000000000005,
        "tone_id" : "sadness",
        "tone_name" : "Sadness"
      },
      {
        "score" : 0.82988799999999996,
        "tone_id" : "analytical",
        "tone_name" : "Analytical"
      }
    ]
  }
}

This time I want to get the values of " score " and " tone_name " in the array " tones " of"document_tone".

Perform JSON parsing

ViewController.swift


let jsonValue = JSON(json)
let tonesScore = jsonValue["document_tone"]["tones"][self.count]["score"].float

First, create a jsonValue with the value json to which the sentiment analysis result is assigned as a JSON. (I'm sorry for the confusing way of saying it lol)

Next, analyze. jsonValue ["document_tone "] ["tones "] [self.count] ["score "] .float You can get the value by specifying like this. It's really simple and easy to understand, isn't it?

As a caveat

(1) It cannot be obtained without understanding the structure of the array of jsonValue which is the analysis result. (2) It is assumed that the self.count used this time defines the member variable count. In addition, self. is described because it is in the closure.

You should now be able to get the score. However, since the score value is redundant as it is, the decimal point is rounded up to obtain it.

ViewController.swift


let jsonValue = JSON(json)
let tonesScore = jsonValue["document_tone"]["tones"][self.count]["score"].float

//Get by rounding up the decimal point of tonesScore
let decimal = tonesScore
let decimalPoint = ceil(decimal! * 100)/100
let tone_score = decimalPoint

Then get the tone_name.

ViewController.swift


let tonesName = jsonValue["document_tone"]["tones"][self.count]["tone_name"].string
let tone_name = tonesName

Now, I think you can get the " score " and the " tone_name " in the array " tones " of the"document_tone", so let's check it withprint (). ..

ViewController.swift


print("=====Confirmation of individual acquisition=====")
print("document_tone.score    : \(tone_score)")
print("document_tone.tone_name: \(tone_name)")

result...

=====Confirmation of individual acquisition=====
document_tone.score    : 0.62
document_tone.tone_name: Optional("Sadness")

You can get it by rounding up the decimal point firmly. By the way, " Sadness " in tone_name means sadness, so you can see that sentiment analysis is also possible.

It's a success!

Finally

This time, I posted about the library SwiftyJSON that makes JSON easy to handle. Recently, I think that there are many opportunities to come into contact with JSON while learning swift. In that sense, Swifty JSON is an indispensable library because it can be described simply.

Please refer to it! Thank you for watching until the end!

Recommended Posts

[Swift5] Get array (individual) information from JSON using library'SwiftyJSON'
[Swift] Use Swity JSON to easily get information from JSON data of the fortune-telling API
[Ethereum] Get block information using web3j
Get caller information from stack trace (java)
[Java] Get tag information from music files
[Ruby] Get unique elements from an array
Get "2-4, 7, 9" from [4, 7, 9, 2, 3]
[Java] Get a random value from an array