Hi guys,
i've been struggling with a problem regarding reading the JSON structure, decoding it and than trying to extract a UNIQUE key structure from it.
So let me show you by example what im trying to do here. Let's take a look at this JSON:
{
"status": true,
"message": "Everything was ok",
"posts":[
{
"id": 1,
"post_type": "type_a",
"posted_on": "",
"updated_on":"",
"user":{
"id": 1,
"name": ""
},
"num_comments": 2,
"comments":[
{
"id": 1,
"comment":"",
"commented_on":"",
"user":{
"id": 1,
"name": "",
"profile_image": ""
}
},
{
"id": "",
"comment": "",
"commented_on": "",
"user":{
"id": "",
"name": "",
"profile_image":""
}
}
],
"message": "",
"images":[
{
"image":"",
"image_large":""
}
]
},
{
"id": 2,
"post_type": "type_b",
"posted_on": "",
"updated_on":"",
"notes":{
"id": 1,
"name": ""
},
"user":{
"id": 1,
"name": ""
},
"num_comments":"0",
"images":[
{
"image":"",
"image_large":""
}
]
},
]
}
So as you can see from the example the structure of the two post arrays varies, one has a comments section, the other one doesnt, one has a notes section, the other one doesnt etc etc. What i would somehow like to be able to do is extract a UNIQUE JSON structure for this document. Meaning i only care about the KEYS not the values and i wanna show the user what can he expect and what are the possibilities.
Here is my code so far:
function keys_are_equal($array1, $array2, $key) {
return !array_diff_key($array1, $array2) && !array_diff_key($array2, $array1);
}
function prettyParseJson($json) {
$decoded = json_decode($json, true);
if($decoded && is_array($decoded)) {
return recursiveJsonRead($decoded);
}
}
function recursiveJsonRead($data) {
$previous_array = array();
$unique_array = array();
foreach ($data as $key => $val) {
if(is_array($val)) {
if(!empty($val)) {
if(keys_are_equal($previous_array, $val, $key)) {
} else {
$unique_array[$key] = gettype($val);
$unique_array[$key] = recursiveJsonRead($val);
$previous_array = $val;
}
}
} else {
$unique_array[$key] = gettype($val);
}
}
return $unique_array;
}
As you can see im trying to decode the json, im trying to walk through it and extract all keys and their types but currently it only works if the structure is ALWAYS the same, if it varies if creates duplicates of keys that are already defined in a previous array. And again i hope im explaing this correctly but all i wanna do is be able to load a JSON file and read out its UNIQUE key structure.
If someone can help me out it would be great cos im losing my mind over it.