Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP - compare the structure of two JSON objects

Tags:

json

object

php

I have two JSON objects and I would like to compare their structure. How can I do it?

Those object are being generated on-the-fly and depending on dynamic content. Which means that the objects are always different but most of the time have the same structure. I want to be able to catch the changes once they occur.

Example: These two objects should be considered as equal, because both have the same structure: index var and tags array.

{
    "index": 0,
    "tags": [
        "abc"
    ]
}
{
    "index": 1,
    "tags": [
        "xyz"
    ]
}

Thoughts?

like image 443
Boarking Avatar asked Aug 17 '15 08:08

Boarking


2 Answers

## You can use this library TreeWalker php .##

TreeWalker is a simple and smal API in php
(I developed this library, i hope it helps you)

It offers two methods
1- Get json difference
2- Edit json value (Recursively)

this method will return the diference between json1 and json2

$struct1 = array("casa"=>1, "b"=>"5", "cafeina"=>array("ss"=>"ddd"), "oi"=>5);
$struct2 = array("casa"=>2, "cafeina"=>array("ss"=>"dddd"), "oi2"=>5);

//P.s
print_r($treeWalker->getdiff($struct1, $struct2))

{
    new: {
        b: "5",
        oi: 5
    },
    removed: {
        oi2: 5
    },
    edited: {
        casa: {
          oldvalue: 2,
          newvalue: 1
        },
        cafeina/ss: {
          oldvalue: "dddd",
          newvalue: "ddd"
        }
    },
    time: 0
}
like image 140
Lucas Cordeiro Avatar answered Sep 21 '22 09:09

Lucas Cordeiro


It's a bit rough, but you get the picture;

$json = '[
        {
            "index": 0,
            "tags": [
                "abc"
            ]
        },
        {
            "index": 1,
            "tags": [
                "xyz"
            ]
        },
        {
            "foo": 2,
            "bar": [
                "xyz"
            ]
        }]';

$array = json_decode($json, true);
$default = array_keys($array[0]);

$error = false;
$errors = array();
foreach ($array as $index => $result):
    foreach ($default as $search):
        if (!isset($result[$search])):
            $error = true;
            $errors[] = "Property '{$search}' at entry '{$index}' not found. ";
        endif;
    endforeach;
endforeach;

if ($error):
    echo 'Objects are not the same. ';
    foreach ($errors as $message):
        echo $message;
    endforeach;
endif;

returns:

Objects are not the same. Property 'index' at entry '2' not found. Property 'tags' at entry '2' not found.

like image 23
vonUbisch Avatar answered Sep 19 '22 09:09

vonUbisch