Parse JSON with PHP

Ingo Foerster
Ingo Foerster used Ask the Experts™
on
I try to parse a JSON file from Java-script (nodes) generated with php. This JSON file has a very depth structure.
As sample:

{
  "application": {
    "title": "Korpuskonfigurator",
    "cart": "Projektverwaltung",
    "nyi": "Noch nicht verfügbar!",
    "dialogs": {
      "username": "Username",
      "id": "ID",
      "name": "Korpusname",
      "errors": {
        "missingFields": "Bitte alle Felder ausfüllen.",
        "specialCharacters": "Keine Sonderzeichen erlaubt!"
      }
    },
    "inspector": {
      "stowageHeight": "Stauhöhe",
      "newValue": "Neuer Wert",
      "firstDrilling": "Erste Bohrung",
      "original": "Original",
      "openOPC": "Ändern",
      "positions": "Positionen",
      "finalPosition": "Final",
      "corrPosition": "Korrekturwert",
      "origPosition": "Originalwert",
      "suggestedPosition": "Vorschlagswert",
      "delta": "Delta"
    },
    "helpmenu": {
      "minz": "Min. Z",
      "maxz": "Max. Z",
      "fov": "Blickfeld"
    }
}

Open in new window


How I can parse this JSON with php So will get for all data the full parameter and value.
As sample:

application.dialogs.errors.specialCharacters = "Keine Sonderzeichen erlaubt!"

Open in new window


So far I have:
$jsonfile = getcwd()."/import/translation_de.json";

$json = file_get_contents($jsonfile);

//Decode JSON
$json_data = json_decode($json,true);

foreach ($json_data as $key1 => $value1) {
    echo $json_data[$key1];
}

Open in new window


But this will fail.
Comment
Watch Question

Do more with

Expert Office
EXPERT OFFICE® is a registered trademark of EXPERTS EXCHANGE®
Swatantra BhargavaTechnical Specialist/Developer

Commented:
Can you provide your JSON file?
Ingo FoersterProgrammer

Author

Commented:
The original file is very big, so I cut out the first part that represents the whole file.

{
  "application": {
    "title": "Korpuskonfigurator",
    "cart": "Projektverwaltung",
    "nyi": "Noch nicht verfügbar!",
    "dialogs": {
      "username": "Username",
      "id": "ID",
      "name": "Korpusname",
      "errors": {
        "missingFields": "Bitte alle Felder ausfüllen.",
        "specialCharacters": "Keine Sonderzeichen erlaubt!"
      }
    },
    "inspector": {
      "stowageHeight": "Stauhöhe",
      "newValue": "Neuer Wert",
      "firstDrilling": "Erste Bohrung",
      "original": "Original",
      "openOPC": "Ändern",
      "positions": "Positionen",
      "finalPosition": "Final",
      "corrPosition": "Korrekturwert",
      "origPosition": "Originalwert",
      "suggestedPosition": "Vorschlagswert",
      "delta": "Delta"
    },
    "helpmenu": {
      "minz": "Min. Z",
      "maxz": "Max. Z",
      "fov": "Blickfeld"
    },
    "cameras": {
      "selectSlot": "Bitte Speicherplatz auswählen"
    }
  }
}

Open in new window

Mark BradyPrincipal Data Engineer

Commented:
You could check for is_array() when checking the values of each key in your loop. If is_array() evaluates to true, you simply involke another foreach loop to parse each level out.
Exploring ASP.NET Core: Fundamentals

Learn to build web apps and services, IoT apps, and mobile backends by covering the fundamentals of ASP.NET Core and  exploring the core foundations for app libraries.

Most Valuable Expert 2018
Distinguished Expert 2018

Commented:
Are you trying to access a particular property of the JSON or simply loop through the whole lot and echo out all the values?

Based on what you've already posted, the reason your code fails is because the first  time you loop through, $key1 is 'application', and $json_data['application'] is an array - you can't call echo on an array. As Mark said, you'd need to loop through that array (and any arrays inside it). Effectively you'd need a recursive loop
Technical Specialist/Developer
Commented:
Try below code, hope this will solve your problem.

$json = '{
  "application": {
    "title": "Korpuskonfigurator",
    "cart": "Projektverwaltung",
    "nyi": "Noch nicht verfügbar!",
    "dialogs": {
      "username": "Username",
      "id": "ID",
      "name": "Korpusname",
      "errors": {
        "missingFields": "Bitte alle Felder ausfüllen.",
        "specialCharacters": "Keine Sonderzeichen erlaubt!"
      }
    },
    "inspector": {
      "stowageHeight": "Stauhöhe",
      "newValue": "Neuer Wert",
      "firstDrilling": "Erste Bohrung",
      "original": "Original",
      "openOPC": "Ändern",
      "positions": "Positionen",
      "finalPosition": "Final",
      "corrPosition": "Korrekturwert",
      "origPosition": "Originalwert",
      "suggestedPosition": "Vorschlagswert",
      "delta": "Delta"
    },
    "helpmenu": {
      "minz": "Min. Z",
      "maxz": "Max. Z",
      "fov": "Blickfeld"
    },
    "cameras": {
      "selectSlot": "Bitte Speicherplatz auswählen"
    }
  }
}';

$data = json_decode( $json, true );
echo "<pre>";
convertJSONtoArray( $data, 0 );
echo "</pre>";
function convertJSONtoArray( $data, $level )
{
	foreach( $data as $key1 => $value1 )
	{
		if( is_array( $value1 ) )
		{
			echo str_repeat( "\t", $level ) . '["' . $key1 . '"] => array (' . "\n";
			convertJSONtoArray( $value1, $level + 1 );
			echo str_repeat( "\t", $level ) . ")," . "\n";
		}
		else
		{
			if( ( $value1=='true' ) or ( $value1=='false' ) or ( is_numeric( $value1 ) ) )  // if numeris or boolean we dont'add quotes
			{
				echo str_repeat( "\t", $level ) . '["' . $key1 . '"] => ' . $value1 . ',' . "\n";
			}
			else
			{
				echo str_repeat( "\t", $level ) . '["' . $key1 . '"] => "' . $value1 . '",' . "\n";
			}
		}
	}
}

Open in new window

Ingo FoersterProgrammer

Author

Commented:
Thank you Swatantra. This was very helpful to write the final function.

Do more with

Expert Office
Submit tech questions to Ask the Experts™ at any time to receive solutions, advice, and new ideas from leading industry professionals.

Start 7-Day Free Trial