json_decode returns a PHP data structure. If you want to serialise that to a JavaScript data structure you have to pass it through json_encode (and then actually echo the string that it returns).

Note that json_encode outputs a JavaScript data structure that is safe for injecting into a <script> element in an HTML document. Not all JSON is safe to do that with (PHP adds additional escape sequences, and will transform plain strings, numbers, null values, etc (which aren't legal JSON on their own).

Note that there is also no point in creating a new array and assigning it to arr if you are going to immediately assign something else to arr.

Also note that '$json_object' will give you a string starting with the $ character and then the name of the variable. Single quoted string in PHP are not interpolated.

var arr;
arr = <?php echo json_encode(json_decode($json_object,TRUE)); ?>;

Also note that this JSON:

{"product_id":"62","product_quantity":"65"}

Will transform in to a PHP associative array or a JavaScript object (which is not an array).

So given this PHP:

<?php
    $json_object = '{"product_id":"62","product_quantity":"65"}';
?>
<script>
    var arr;
    arr = <?php echo json_encode(json_decode($json_object,TRUE)); ?>;
    alert(arr.product_id);
</script>

You get this output:

<script>
    var arr;
    arr = {"product_id":"62","product_quantity":"65"};
    alert(arr.product_id);
</script>

Which alerts 62 when run.

Answer from Quentin on Stack Overflow
🌐
W3Schools
w3schools.com › php › func_json_decode.asp
PHP json_decode() Function
Store JSON data in a PHP variable, and then decode it into a PHP object.
🌐
PHP
php.net › manual › en › function.json-decode.php
PHP: json_decode - Manual
Returns the value encoded in json as an appropriate PHP type. Unquoted values true, false and null are returned as true, false and null respectively. null is returned if the json cannot be decoded or if the encoded data is deeper than the nesting ...
🌐
Tutorialspoint
tutorialspoint.com › php › php_function_javascript_object_notation_json_decode.htm
PHP - json_decode() Function
<?php // Assign a JSON object to a variable $someJSON = '{"name" : "Raja", "Adithya" : "Jai"}'; // Convert the JSON to an associative array $someArray = json_decode($someJSON, true); // Read the elements of the associative array foreach($someArray ...
🌐
ReqBin
reqbin.com › code › php › zg4d50d8 › php-json-decode-example
How do I decode JSON in PHP?
July 7, 2023 - In PHP, the json_decode() function is used to decode JSON strings into PHP objects. The result object can be any PHP data type except for resource pointers such as a database or file descriptor.
Top answer
1 of 3
6

json_decode returns a PHP data structure. If you want to serialise that to a JavaScript data structure you have to pass it through json_encode (and then actually echo the string that it returns).

Note that json_encode outputs a JavaScript data structure that is safe for injecting into a <script> element in an HTML document. Not all JSON is safe to do that with (PHP adds additional escape sequences, and will transform plain strings, numbers, null values, etc (which aren't legal JSON on their own).

Note that there is also no point in creating a new array and assigning it to arr if you are going to immediately assign something else to arr.

Also note that '$json_object' will give you a string starting with the $ character and then the name of the variable. Single quoted string in PHP are not interpolated.

var arr;
arr = <?php echo json_encode(json_decode($json_object,TRUE)); ?>;

Also note that this JSON:

{"product_id":"62","product_quantity":"65"}

Will transform in to a PHP associative array or a JavaScript object (which is not an array).

So given this PHP:

<?php
    $json_object = '{"product_id":"62","product_quantity":"65"}';
?>
<script>
    var arr;
    arr = <?php echo json_encode(json_decode($json_object,TRUE)); ?>;
    alert(arr.product_id);
</script>

You get this output:

<script>
    var arr;
    arr = {"product_id":"62","product_quantity":"65"};
    alert(arr.product_id);
</script>

Which alerts 62 when run.

2 of 3
0

You could push the JSON objects into javascript array and iterate through the array, selecting the appropriate fields you need. Fixed it..

    var json = {"product_id":"62","product_quantity":"65"}; 
    var array = new Array();
    array.push(json);   
    for(var i = 0; i < array.length; i++){
       console.log(array[i].product_id)
    }
🌐
Locutus
locutus.io › php › json › json_decode
PHP's json_decode in JavaScript | Locutus
January 19, 2026 - You you can install via yarn add locutus and require this function via const json_decode = require('locutus/php/json/json_decode').
🌐
Code Beautify
codebeautify.org › json-decode-online
JSON Decode Online to decode JSON to readable form.
JSON Decode Online is easy to use tool to decode JSON data, view JSON data in hierarchy and show as json_decode php.
Find elsewhere
🌐
Jsondecode
jsondecode.com › decode-json
JSON Decoder Online — Decode JSON Instantly | Free JSON Parser | jsondecode.com
Free online JSON decoder and parser. Paste JSON, decode it instantly, and see errors highlighted by line. Includes JavaScript, Python, and PHP code examples.
🌐
WEB sandbox.ws
sandbox.ws › en › php-functions › json-encode-decode
Online JSON Tool - Encode/Decode JSON Data via PHP function.
Free online JSON encoder and decoder using PHP json_encode() and json_decode() functions.
🌐
Jonathan Suh
jonsuh.com › blog › convert-loop-through-json-php-javascript-arrays-objects
Convert and Loop through JSON with PHP and JavaScript Arrays/Objects — Jonathan Suh
September 30, 2014 - If you’re working with JSON ... take an array or object and convert it to a JSON string to return, both can be done in PHP or JavaScript. ... PHP >= 5.2.0 features a function, json_decode, that decodes a JSON string into a PHP variable...
🌐
Tutorial Republic
tutorialrepublic.com › php-tutorial › php-json-parsing.php
How to Encode and Decode JSON Data in PHP - Tutorial Republic
JSON data structures are very similar to PHP arrays. PHP has built-in functions to encode and decode JSON data. These functions are json_encode() and json_decode(), respectively.
Top answer
1 of 5
6

The problem that you're running into is that the output of json_encode is not meant to be used directly as a string in JavaScript.

json_encode outputs a usable JavaScript object:

<?php
$foo = new stdClass();
$foo->test='hello world';
$bar = new stdClass();
$bar->foo = json_encode($foo);
$encoded_string = json_encode($bar);
?>
var a = <?php $encoded_string ?>;
console.log(a.foo); // produces '{"test":"hello world"}'

If you want to needlessly parse the JSON output from a string value, you simply need to double encode $encoded_string:

<?php
$foo = new stdClass();
$foo->test='hello world';
$bar = new stdClass();
$bar->foo = json_encode($foo);
$encoded_string = json_encode(json_encode($bar));
?>
var aStr = <?php $encoded_string ?>;
var a = JSON.parse(aStr);
console.log(a.foo); //same as before

Of course, you should avoid using server side languages to generate JavaScript code, instead set up the data as either a data-* attribute or as a JSON source that can be requested with AJAX.

When the data is requested from the server (or from the attribute) it will be as a properly escaped JavaScript string, which is where JSON.parse will be necessary to parse the object.

2 of 5
2

Your code should be

$foo = new stdClass();
$foo->test='hello world';
$bar = new stdClass();
$bar->foo = $foo;
$encoded_string = json_encode($bar);

Just json encode once at the end, and decode once at the beginning at the other end.


As for the jsfiddle, you are not considering that the string literals go through additional decoding layer before they become "strings in javascript memory".

The correct way to setup the string literal in this case is (JS-JSON-JSON):

data = $.parseJSON('{"foo":"{\\\"test\\\":\\\"hello world\\\"}"}');
console.log($.parseJSON(data.foo));

And simply reversing the encoding steps you did works. http://jsfiddle.net/Jmjjp/2/

🌐
PHPpot
phppot.com › php › json-handling-with-php-how-to-encode-write-parse-decode-and-convert
PHP JSON Encode and Decode with json_encode() and json_decode() - PHPpot
Objects become arrays or objects based on your decode mode, and JSON arrays remain ordered lists. If you are reading JSON submitted from JavaScript, APIs, or external services, json_decode() is usually the first function ...
🌐
SitePoint
sitepoint.com › php
Encoding/Decoding JSON PHP - PHP - SitePoint Forums | Web Development & Design Community
February 19, 2023 - I can do this with Javascript, so needing to be schooled in PHP on how to do this. Please help. ... Just replace the backslash double quotes by double quotes and decode it. $data = json_decode(st...
🌐
Functions-Online
functions-online.com › json_decode.html
test json_decode online - general PHP functions - functions-online
Test and run json_decode online in your browser. Json_decode() takes a JSON encoded string and converts it into a PHP variable.
🌐
OnlinePHP
onlinephp.io › json-decode › examples
json_decode - Examples
PHP Functions · Donate/Get Premium · Login / Register · OnlinePHP.io · Documentation · json_decode · Examples · PHP 5 >= 5.2.0, PHP 7, PHP 8, PECL json >= 1.2.0 · json_decode - Decodes a JSON string · Json Decode Online Tool · Manual · Code Examples ·
🌐
PHPHub
phphub.net › home › json_decode online
json_decode PHP online
May 11, 2025 - Execute PHP’s json_decode() function. Convert JSON to PHP value quickly and easily with this web-based PHP tool.
🌐
W3docs
w3docs.com › home › learn php › json_decode
Understanding the json_decode Function in PHP | W3docs
The json_decode function in PHP is an essential tool for developers who work with JSON (JavaScript Object Notation) data. This function converts a
🌐
OnlinePHP
onlinephp.io › json-decode
json_decode - Online Tool
# Execute and compare PHP Online · Sandbox · PHP Functions · Donate/Get Premium · Login / Register · Home · PHP Functions · General · json_decode · Execute json_decode with this online tool json_decode() - Decodes a JSON string · Json ...