Create an account


Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
[Tut] Convert JSON to Array in PHP with Online Demo

#1
Convert JSON to Array in PHP with Online Demo

<div style="margin: 5px 5% 10px 5%;"><img src="https://www.sickgaming.net/blog/wp-content/uploads/2022/10/convert-json-to-array-in-php-with-online-demo.jpg" width="550" height="269" title="" alt="" /></div><div><div class="modified-on" readability="7.1304347826087"> by <a href="https://phppot.com/about/">Vincy</a>. Last modified on October 27th, 2022.</div>
<p>This tutorial covers the basic details of the PHP <em>json_encode</em> function. It gives examples of <a href="https://phppot.com/php/php-object-to-array/">decoding JSON string input</a> to a PHP array.</p>
<p>It also describes this <a href="https://phppot.com/php/json-handling-with-php-how-to-encode-write-parse-decode-and-convert/">PHP JSON function</a>‘s conventions, rules and limitations. First, let’s see a quick example of converting JSON to an array.</p>
<h2>Convert JSON to PHP Array</h2>
<p>This example has a JSON string that maps the animal with its count. The output of converting this JSON will return an associative array.</p>
<p>It uses PHP json_decode() with boolean true as its second parameter. With these decoding params, the JSON will be converted into a PHP array.</p>
<div class="post-section-highlight" readability="38">
<h3>Quick example</h3>
<pre class="prettyprint"><code class="language-php">&lt;?php
// JSON string in PHP Array
$jsonString = '{"Lion":101,"Tiger":102,"Crocodile":103,"Elephant":104}';
$phpArray = json_decode($jsonString, true); // display the converted PHP array
var_dump($phpArray);
?&gt;
</code></pre>
</div>
<h3>Output</h3>
<pre class="prettyprint"><code>array(4) { ["Lion"]=&gt; int(101) ["Tiger"]=&gt; int(102) ["Crocodile"]=&gt; int(103) ["Elephant"]=&gt; int(104)
}
</code></pre>
<p>See this online demo to get the converted array result from a JSON input.<br /><a class="demo" href="https://phppot.com/demo/php-json-to-array/">View demo</a></p>
<p>See the diagram that shows the input JSON string and the output stdClass object of the JSON decoding. In the previous article, we have seen examples of the reverse operation that is <a href="https://phppot.com/php/php-array-to-json/">converting a PHP array to a JSON string</a>.<br /><img loading="lazy" class="alignnone size-large wp-image-19889" src="https://phppot.com/wp-content/uploads/2022/10/php-json-to-array-550x269.jpg" alt="php json to array" width="550" height="269" srcset="https://phppot.com/wp-content/uploads/2022/10/php-json-to-array-550x269.jpg 550w, https://phppot.com/wp-content/uploads/20...00x147.jpg 300w, https://phppot.com/wp-content/uploads/20...68x376.jpg 768w, https://phppot.com/wp-content/uploads/20...-array.jpg 972w" sizes="(max-width: 550px) 100vw, 550px"></p>
<h2>PHP <em>json_decode()</em></h2>
<p>This native PHP function <a href="https://phppot.com/php/php-json-encode-and-decode/">decodes the JSON string</a> into a parsable object tree or an array. This is the syntax of this function.</p>
<pre class="prettyprint"><code class="language-php">json_decode( string $json, ?bool $associative = null, int $depth = 512, int $flags = 0
): mixed
</code></pre>
<ol>
<li>$json – Input JSON string.</li>
<li>$associative – a boolean based on which the output format varies between an associative array and a stdClass object.</li>
<li>$depth – the allowed nesting limit.</li>
<li>$flag – Predefine constants to enable features like exception handling during the JSON to array convert.</li>
</ol>
<p>You can find more about this function in the <a href="https://www.php.net/manual/en/function.json-decode.php" target="_blank" rel="noopener">official documentation</a> online.</p>
<h2>Convert JSON to PHP Object</h2>
<p>This program has a minute change of not setting the boolean flag to the PHP json_decode function. This will return a PHP stdClass object tree instead of an array.</p>
<pre class="prettyprint"><code class="language-php">&lt;?php
// JSON string in PHP Array
$jsonString = '{"name":"Lion"}'; $phpObject = json_decode($jsonString);
print $phpObject-&gt;name;
?&gt;
</code></pre>
<h3>Output</h3>
<pre class="prettyprint"><code>Lion
</code></pre>
<h2>Common mistakes during conversion from JSON to Array</h2>
<p>The following JSON string is a valid JSON object in JavaScript, but not here in PHP. The issue is the single quote. It should be changed to a double quote.</p>
<p>If you want to see the JavaScript example to <a href="https://phppot.com/jquery/read-display-json-data-using-jquery-ajax/">read and display JSON data</a> the linked article has the code.</p>
<pre class="prettyprint"><code class="language-php">&lt;?php
// 1. key and value should be within double quotes
$notValidJson = "{ 'lion': 'animal' }";
json_decode($notValidJson); // will return null // 2. without a quote is also not allowed
$notValidJson = '{ lion: "animal" }';
json_decode($notValidJson); // will return null // 3. should not have a comma at the end
$notValidJson = '{ "lion": "animal", }';
json_decode($notValidJson); // will return null
?&gt;
</code></pre>
<h2>How to convert JSON with large integers</h2>
<p>This can be achieved by setting the bitmask parameter of the predefined JSON constants.</p>
<p>The JSON_BIGINT_AS_STRING constant is used to convert JSON with data having large integers.</p>
<pre class="prettyprint"><code class="language-php">&lt;?php
$jsonString = '{"largeNumber": 12345678901234567890123}'; var_dump(json_decode($jsonString, false, 512, JSON_BIGINT_AS_STRING));
?&gt;
</code></pre>
<h3>Output</h3>
<pre class="prettyprint"><code>object(stdClass)#1 (1) { ["number"]=&gt; string(20) "12345678901234567890123"
}
</code></pre>
<h2>How to get errors when using json_decode</h2>
<p>The function json_last_error() is used to return details about the last error occurrence. The following example handles the possible error cases of this PHP JSON function.</p>
<pre class="prettyprint"><code class="language-php">&lt;?php
$jsonString = '{"Lion":101,"Tiger":102,"Crocodile":103,"Elephant":104}';
json_decode($jsonString); switch (json_last_error()) { case JSON_ERROR_DEPTH: echo 'Error: Nesting limit exceeded.'; break; case JSON_ERROR_STATE_MISMATCH: echo 'Error: Modes mismatch.'; break; case JSON_ERROR_CTRL_CHAR: echo 'Error: Unexpected character found.'; break; case JSON_ERROR_SYNTAX: echo 'Error: Syntax error, invalid JSON.'; break; case JSON_ERROR_UTF8: echo 'Error: UTF-8 characters incorrect encoding.'; break; default: echo 'Unexpected error.'; break;
}
?&gt;
</code></pre>
<h2>SURPRISE! JSON to Array and Array to JSON conversion is not symmetrical</h2>
<pre class="prettyprint"><code class="language-php">&lt;?php $jsonString = '{"0": "No", "1": "Yes"}'; // convert json to an associative array $array = json_decode($jsonString, true); print json_encode($array) . PHP_EOL;
?&gt;
</code></pre>
<h3>Output</h3>
<pre class="prettyprint"><code>["No","Yes"]
</code></pre>
<p>The PHP object is now changed to a PHP array. You may not expect it.</p>
<pre class="prettyprint"><code>Encode -&gt; Decode -&gt; Encode
</code></pre>
<p>The above will not return the data to its original form.</p>
<p>The output of decoding to PHP arrays and encoding from PHP arrays are not always symmetrical. But, the output of decoding from stdClass objects and encoding to stdClass objects are always symmetrical.</p>
<p>So if you have plans to do cyclical conversion between the PHP array and a JSON string, then first convert the PHP array to an object. The convert the JSON.</p>
<p><a class="demo" href="https://phppot.com/demo/php-json-to-array/">View demo</a></p>
<p> <!-- #comments --> </p>
<div class="related-articles">
<h2>Popular Articles</h2>
</p></div>
<p> <a href="https://phppot.com/php/json-to-array-php/#top" class="top">↑ Back to Top</a> </p>
</div>


https://www.sickgaming.net/blog/2022/10/...line-demo/
Reply



Forum Jump:


Users browsing this thread:
2 Guest(s)

Forum software by © MyBB Theme © iAndrew 2016