Skip to content
Tags

,

JSON Compare (for PHP)

December 3, 2014

I was looking for a diff command to compare two JSON file. I didn’t found the expected code then I wrote it. Basically, it is not very complex if you think about arrays rather than plain text.

I have implemented the code in PHP and made a test suite but I was not able to provide it immediately. I rather give you a PHP to compare PHP arrays:

https://gist.github.com/wrey75/c631f6fe9c975354aec7

Of course, you can use json_encode() and json_decode() if you are interested by working on JSON files: for your information, I used these methods for the PHPUnit tests.

How it works?

I provide a JSONUtils class. And you have two functions in it: one to get the differences and another to patch. The difference is an array (which can be empty) and this difference is made of arrays containing “new” and “old” values (and “upd” when you have sub-arrays): it means that you can compare two arrays and save only the differences. It is a ideal way to do to save an history of changes on a SQL record.

The main advantage of this structure is to remain clear and human-readable. The other advantage is to be able to patch changes and to be able to reverse them.

For those who works with PHP, you know the language does a mix between lists and hash tables. Then, the class has some improvements to do. You should use an explicit index for each object of an array. Nevertheless, we do our best to keep the arrays ordered. Sometimes it is simply not enough.

Advertisements

From → Computers

Leave a Comment

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: