• Open Menu Close Menu
  • Apple
  • Shopping Bag
  • Apple
  • Mac
  • iPad
  • iPhone
  • Watch
  • TV
  • Music
  • Support
  • Search apple.com
  • Shopping Bag

Lists

Open Menu Close Menu
  • Terms and Conditions
  • Lists hosted on this site
  • Email the Postmaster
  • Tips for posting to public mailing lists
Re: Checking if a string is valid JSON
[Date Prev][Date Next][Thread Prev][Thread Next][Date Index][Thread Index]

Re: Checking if a string is valid JSON


  • Subject: Re: Checking if a string is valid JSON
  • From: Quincey Morris <email@hidden>
  • Date: Mon, 29 Jan 2018 13:25:51 -0800

On Jan 29, 2018, at 12:42 , Eric E. Dolecki <email@hidden> wrote:
>
> So this would do it?

I would strongly recommend using JSONDecoder instead of JSONSerialization. The
errors JSONDecoder throws are AFAIK more detailed than JSONSerialization, and
will tell you the exact location in the string of any error you find.

Also, FWIW, I beg you not to use this pattern (if you actually do, outside of
this sample fragment):

>        let jsonData = jsonString.data(using: String.Encoding.utf8)
>       …
>            _ = try JSONSerialization.jsonObject(with: jsonData!)


but do this instead:

>        let jsonData = jsonString.data(using: String.Encoding.utf8)!
>       …
>            _ = try JSONSerialization.jsonObject(with: jsonData)


That is, don’t let optionals “escape” from the place where they first appear.
If, in real code, you’re going to make the string decoding failure a handled
error too, then this would of course become:

>        if let jsonData = jsonString.data(using: String.Encoding.utf8) {
>       …
>       …
>            _ = try JSONSerialization.jsonObject(with: jsonData)


where the optional still doesn’t escape from its point of appearance.

_______________________________________________

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

  • Follow-Ups:
    • Re: Checking if a string is valid JSON
      • From: Saagar Jha <email@hidden>
References: 
 >Checking if a string is valid JSON (From: "Eric E. Dolecki" <email@hidden>)
 >Re: Checking if a string is valid JSON (From: Saagar Jha <email@hidden>)
 >Re: Checking if a string is valid JSON (From: "Eric E. Dolecki" <email@hidden>)

  • Prev by Date: Re: Checking if a string is valid JSON
  • Next by Date: Re: Checking if a string is valid JSON
  • Previous by thread: Re: Checking if a string is valid JSON
  • Next by thread: Re: Checking if a string is valid JSON
  • Index(es):
    • Date
    • Thread