Parse JSON with PHP

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.
Ingo FoersterProgrammerAsked:
Who is Participating?
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Swatantra BhargavaTechnical Specialist/DeveloperCommented:
Can you provide your JSON file?
0
Ingo FoersterProgrammerAuthor 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

0
Mark BradyPrincipal Data EngineerCommented:
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.
0
CompTIA Security+

Learn the essential functions of CompTIA Security+, which establishes the core knowledge required of any cybersecurity role and leads professionals into intermediate-level cybersecurity jobs.

Chris StanyonWebDevCommented:
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
0
Swatantra BhargavaTechnical Specialist/DeveloperCommented:
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

1

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
Ingo FoersterProgrammerAuthor Commented:
Thank you Swatantra. This was very helpful to write the final function.
0
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.