2

All the examples I find are using dictionary types, for example: user: x, book: y

but how can I convert this type of Json which doesn't contain a key?

["1","137","56","56"]

This is of type String?

I tried:

struct Candidate: Decodable {
    var S: String?
}

let chainsAllowed = ["1","137","56","56"]

let jsonObjectData = chainsAllowed.data(using: .utf8)!
let candidate = try? JSONDecoder().decode(
    Candidate.self,
    from: jsonObjectData
)

but I get nil. How can I convert it into an array?

Thanks

7
  • '["1","137","56","56"]' is not even in the JSON format, duh... Commented Aug 11, 2021 at 2:00
  • JSON format be like ["userA": "1", "userB": "137", "userC": "56", "userD": "56"], bro Commented Aug 11, 2021 at 2:04
  • 2
    try? is literally saying "If there are any errors, please disregard them and just give me nil". If you caught the error instead and took a look at it, you would have gotten a useful error message. Commented Aug 11, 2021 at 2:18
  • 1
    For anyone saying it's not even JSON, it actually is valid JSON. A JSON text can be any of false / null / true / object / array / number / string. See datatracker.ietf.org/doc/html/rfc8259#section-2 Commented Aug 11, 2021 at 2:23
  • @ElTomato lol it is. It's actually downloaded from AWS DyanamoDB with type: AWSJSON Commented Aug 11, 2021 at 2:26

1 Answer 1

4

Do this:

import Foundation

let chainsAllowed = #"["1","137","56","56"]"#

let jsonObjectData = chainsAllowed.data(using: .utf8)
let candidate = try? JSONDecoder().decode(
    [String].self,
    from: jsonObjectData!
)

print(candidate!)

Output:

["1", "137", "56", "56"]

For your information: An array is actually perfectly valid JSON. In fact, a JSON text can be any of false / null / true / object / array / number / string. See https://datatracker.ietf.org/doc/html/rfc8259#section-2

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.