user2261146
user2261146

Reputation: 15

PHP json parser - off the shelf or roll my own?

I'm sorry if this seems like a newbie question but I am a newbie - so please be explicit in answers. I also hope that the terminology that I’m using is correct and doesn’t confuse the issue.

I need to parse a json file but I have no control over the content / structure and when the content changes the first I’ll know about it will probably be when I try to read it. My approach will be to work through the data and validate that I recognise each data item and that it’s context is as I expect, so that it’s handled correctly as I insert it into the database.

It seems to me (in my blissful ignorance) that there’s little difference in walking through an array produced by e.g. by PHP json_decode () or walking through the json, with my own specialised parser that will validate the json data as I parse it.

So my question is am I missing something here e.g. a big gotcha that's going to make parsing the json more complex than I expect or maybe I’m missing the point in some other way?

Upvotes: 1

Views: 86

Answers (2)

Jon Surrell
Jon Surrell

Reputation: 9647

I recommend using json_decode. It will handle turning valid JSON into a PHP data structure. Then it should be much more natural to work with. Not to mention there are probably a lot of things you could get wrong in the parser that you won't have to worry about because json_decode will handle it.

Once you've got a PHP data structure, then work with that. Do your validation etc. there.

Upvotes: 1

Boon Xiong
Boon Xiong

Reputation: 21

I'm a bit confused as to what your question is. I would recommend sticking with json_decode() and not to write your own parser as your's would probably end up simulating json_decode() anyways.

You can validate your json values as you move down each propery however you like.

Upvotes: 1

Related Questions