Re: Checking if a string is valid JSON
Re: Checking if a string is valid JSON
- Subject: Re: Checking if a string is valid JSON
- From: Saagar Jha <email@hidden>
- Date: Mon, 29 Jan 2018 12:34:42 -0800
I believe jsonObject(with:options) will throw if the JSON is invalid, so you
might be able to get away with just the try/catch. Besides, your JSON top level
object might be an array, in which case I’d expect that casting to an
NSDictionary would fail.
Saagar Jha
> On Jan 29, 2018, at 12:17, Eric E. Dolecki <email@hidden> wrote:
>
> I am generating a String of JSON. Before I use it, I want to check to make
> sure that it's valid. My code is below. Does this look alright?
>
> Thanks,
> Eric
>
>
>
> let jsonString = composedString
>
> let jsonData = jsonString.data(using: String.Encoding.utf8)
>
> do {
>
> if (try JSONSerialization.jsonObject(with: jsonData!, options:
> []) as? NSDictionary) != nil {
>
> print("JSON is a dictionary. Valid.")
>
> } else {
>
> print("Not valid JSON data.")
>
> }
>
> } catch let error as NSError {
>
> print("Not valid JSON. \(error.localizedDescription)")
>
> }
> _______________________________________________
>
> Cocoa-dev mailing list (email@hidden)
>
> Please do not post admin requests or moderator comments to the list.
> Contact the moderators at cocoa-dev-admins(at)lists.apple.com
>
> Help/Unsubscribe/Update your Subscription:
>
> This email sent to email@hidden
_______________________________________________
Cocoa-dev mailing list (email@hidden)
Please do not post admin requests or moderator comments to the list.
Contact the moderators at cocoa-dev-admins(at)lists.apple.com
Help/Unsubscribe/Update your Subscription:
This email sent to email@hidden