简体   繁体   中英

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 eg 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 eg 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?

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM