Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

217
Views
Why does json_encode returns object instead of string?

PHP json_encode

Returns a string containing the JSON representation of the supplied value. php.net

but it returns JavaScript object not a Json string:

  <script>
   var app = <?php echo json_encode($array); ?>;
   alert(app.name)
 </script>
about 4 years ago · Juan Pablo Isaza
2 answers
Answer question

0

but it returns JavaScript object not a Json string:

Context matters, consider this code:

<?php
$array = ['name' => 'John Doe'];
$string = json_encode($array);
var_dump($string);

Executing that produces:

$ php index.php
string(19) "{"name":"John Doe"}"

string(19) means the variable is a string of 19 characters. The fact that string can be interpretted by js as an object is immaterial here, to php it is producing a string.

about 4 years ago · Juan Pablo Isaza Report

0

but it returns JavaScript object not a Json string

You skip a few steps here:

  1. json_encode returns a string in PHP
  2. That string is given to the echo statement
  3. Everything that is output, is passed as the HTML page for the browser to interpret
  4. The browser uses its JavaScript engine to parse the scripts that are part of the page -- that JSON is parsed as any other object literal that might occur in the script.
  5. To the JavaScript engine, this part of the script is not a string, but an object literal.

It may help to rewrite the PHP script to something that is equivalent:

echo "
  <script>
   var app = " . json_encode($array) . ";
   alert(app.name)
 </script>";

So now it is clear that PHP sends one string, which happens to represent valid JavaScript -- enclosed in a <script> tag. The JSON is just a part of that long string, which later the browser will parse, and where the JavaScript part is parsed by a JavaScript engine.

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!