Help us understand the problem. What is going on with this article?

swiftでのJSONの扱い方

More than 1 year has passed since last update.

書いた理由

JSONの扱い方が僕には複雑だったのでまとめ

JSONの扱い方

jsonPractice.swift
//Stringスタート
let initJSONStr = "[{\"question\":\"str\",\"answers\":[\"Str1\",\"Str2\"]},{\"question\":\"str\",\"answers\":[\"Str1\",\"Str2\"]}]"
//StringからDataへ
let data = initJSONStr.data(using: .utf8)!
//DataからJSONObjectへ
let json = try? JSONSerialization.jsonObject(with: data, options: [])
//JSONObjectからArrayへ
var array:Array<Dictionary<String,Any>> = []
//jsonの中身がちゃんとarrayにできるかを確認
if let checkArray = json as? [Dictionary<String,Any>]{
        array = checkArray
}
//arrayを適当に編集
array[0]["question"] = "aaa"
var newQuestion:Dictionary<String,Any> = ["question":"new","answers":["答え1","答え2"]]
array.append(newQuestion)
//ArrayからData
let data2 = try JSONSerialization.data(withJSONObject: array, options: [])
//DataからString
let jsonStr = String(bytes: data2, encoding: .utf8)!
print(jsonStr)//[{"question":"aaa","answers":["Str1","Str2"]},{"question":"str","answers":["Str1","Str2"]},{"answers":["答え1","答え2"],"question":"new"}]

Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away