Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

218
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda