mirror of
https://github.com/php/doc-es.git
synced 2026-03-24 15:32:36 +01:00
397 lines
10 KiB
XML
397 lines
10 KiB
XML
<?xml version="1.0" encoding="utf-8"?>
|
|
<!-- $Revision$ -->
|
|
<!-- EN-Revision: 9f2e30a00afda6d6b6a3e19b13956150c2eaf2c1 Maintainer: PhilDaiguille Status: ready -->
|
|
<!-- Reviewed: yes -->
|
|
<refentry xml:id="function.json-decode" xmlns="http://docbook.org/ns/docbook">
|
|
<refnamediv>
|
|
<refname>json_decode</refname>
|
|
<refpurpose>Decodifica una cadena JSON</refpurpose>
|
|
</refnamediv>
|
|
|
|
<refsect1 role="description">
|
|
&reftitle.description;
|
|
<methodsynopsis>
|
|
<type>mixed</type><methodname>json_decode</methodname>
|
|
<methodparam><type>string</type><parameter>json</parameter></methodparam>
|
|
<methodparam choice="opt"><type class="union"><type>bool</type><type>null</type></type><parameter>associative</parameter><initializer>&null;</initializer></methodparam>
|
|
<methodparam choice="opt"><type>int</type><parameter>depth</parameter><initializer>512</initializer></methodparam>
|
|
<methodparam choice="opt"><type>int</type><parameter>flags</parameter><initializer>0</initializer></methodparam>
|
|
</methodsynopsis>
|
|
<para>
|
|
Recupera una cadena codificada en JSON y la convierte en un valor de PHP.
|
|
</para>
|
|
</refsect1>
|
|
|
|
<refsect1 role="parameters">
|
|
&reftitle.parameters;
|
|
<para>
|
|
<variablelist>
|
|
<varlistentry>
|
|
<term><parameter>json</parameter></term>
|
|
<listitem>
|
|
<para>
|
|
La &string; <parameter>json</parameter> a decodificar.
|
|
</para>
|
|
<para>
|
|
Esta función solo funciona con cadenas codificadas en UTF-8.
|
|
</para>
|
|
&json.implementation.superset;
|
|
</listitem>
|
|
</varlistentry>
|
|
<varlistentry>
|
|
<term><parameter>associative</parameter></term>
|
|
<listitem>
|
|
<para>
|
|
Cuando este parámetro vale &true;, los objetos JSON serán devueltos como
|
|
arrays asociativos; cuando este parámetro vale &false;, los objetos JSON
|
|
serán devueltos como objetos. Cuando este parámetro vale &null;, los objetos
|
|
JSON serán devueltos como arrays asociativos o como objetos, según si la constante
|
|
<constant>JSON_OBJECT_AS_ARRAY</constant> ha sido definida en el parámetro <parameter>flags</parameter>.
|
|
</para>
|
|
</listitem>
|
|
</varlistentry>
|
|
<varlistentry>
|
|
<term><parameter>depth</parameter></term>
|
|
<listitem>
|
|
<para>
|
|
Profundidad máxima de anidamiento de la estructura en proceso de decodificación.
|
|
El valor debe ser superior a <literal>0</literal>,
|
|
e inferior o igual a <literal>2147483647</literal>.
|
|
</para>
|
|
</listitem>
|
|
</varlistentry>
|
|
<varlistentry>
|
|
<term><parameter>flags</parameter></term>
|
|
<listitem>
|
|
<para>
|
|
Máscara de bits compuesta por
|
|
<constant>JSON_BIGINT_AS_STRING</constant>,
|
|
<constant>JSON_INVALID_UTF8_IGNORE</constant>,
|
|
<constant>JSON_INVALID_UTF8_SUBSTITUTE</constant>,
|
|
<constant>JSON_OBJECT_AS_ARRAY</constant>,
|
|
<constant>JSON_THROW_ON_ERROR</constant>.
|
|
El comportamiento de estas constantes se describe en la página
|
|
de las <link linkend="json.constants">constantes JSON</link>.
|
|
</para>
|
|
</listitem>
|
|
</varlistentry>
|
|
</variablelist>
|
|
</para>
|
|
</refsect1>
|
|
|
|
<refsect1 role="returnvalues">
|
|
&reftitle.returnvalues;
|
|
<para>
|
|
Devuelve el valor codificado en el parámetro <parameter>json</parameter>
|
|
en el tipo PHP apropiado. Los valores sin comillas <literal>true</literal>,
|
|
<literal>false</literal> y <literal>null</literal>
|
|
son devueltos respectivamente como &true;, &false; y &null;.
|
|
&null; es devuelto si el parámetro <parameter>json</parameter> no ha podido
|
|
ser decodificado o si los datos codificados son más profundos que el límite
|
|
de anidamiento proporcionado.
|
|
</para>
|
|
</refsect1>
|
|
|
|
<refsect1 role="errors">
|
|
&reftitle.errors;
|
|
<para>
|
|
Si <parameter>depth</parameter> está fuera del rango permitido,
|
|
una <classname>ValueError</classname> es lanzada a partir de PHP 8.0.0,
|
|
mientras que anteriormente se generaba un error de nivel <constant>E_WARNING</constant>.
|
|
</para>
|
|
</refsect1>
|
|
|
|
<refsect1 role="changelog">
|
|
&reftitle.changelog;
|
|
<para>
|
|
<informaltable>
|
|
<tgroup cols="2">
|
|
<thead>
|
|
<row>
|
|
<entry>&Version;</entry>
|
|
<entry>&Description;</entry>
|
|
</row>
|
|
</thead>
|
|
<tbody>
|
|
<row>
|
|
<entry>7.3.0</entry>
|
|
<entry>
|
|
El <parameter>flags</parameter>
|
|
<constant>JSON_THROW_ON_ERROR</constant> ha sido añadido.
|
|
</entry>
|
|
</row>
|
|
<row>
|
|
<entry>7.2.0</entry>
|
|
<entry>
|
|
El parámetro <parameter>associative</parameter> ahora es nullable.
|
|
</entry>
|
|
</row>
|
|
<row>
|
|
<entry>7.2.0</entry>
|
|
<entry>
|
|
Los <parameter>flags</parameter>
|
|
<constant>JSON_INVALID_UTF8_IGNORE</constant>, y
|
|
<constant>JSON_INVALID_UTF8_SUBSTITUTE</constant> han sido añadidos.
|
|
</entry>
|
|
</row>
|
|
<row>
|
|
<entry>7.1.0</entry>
|
|
<entry>
|
|
Una clave JSON vacía ("") puede ser codificada en la propiedad de objeto
|
|
vacía en lugar de usar una clave con el valor <literal>_empty_</literal>.
|
|
</entry>
|
|
</row>
|
|
</tbody>
|
|
</tgroup>
|
|
</informaltable>
|
|
</para>
|
|
</refsect1>
|
|
|
|
<refsect1 role="examples">
|
|
&reftitle.examples;
|
|
<para>
|
|
<example>
|
|
<title>Ejemplo con <function>json_decode</function></title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
$json = '{"a":1,"b":2,"c":3,"d":4,"e":5}';
|
|
|
|
var_dump(json_decode($json));
|
|
var_dump(json_decode($json, true));
|
|
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
&example.outputs;
|
|
<screen>
|
|
<![CDATA[
|
|
object(stdClass)#1 (5) {
|
|
["a"] => int(1)
|
|
["b"] => int(2)
|
|
["c"] => int(3)
|
|
["d"] => int(4)
|
|
["e"] => int(5)
|
|
}
|
|
|
|
array(5) {
|
|
["a"] => int(1)
|
|
["b"] => int(2)
|
|
["c"] => int(3)
|
|
["d"] => int(4)
|
|
["e"] => int(5)
|
|
}
|
|
]]>
|
|
</screen>
|
|
</example>
|
|
<example>
|
|
<title>Acceso a propiedades de objeto inválidas</title>
|
|
<simpara>
|
|
Acceder a elementos de un objeto que contienen caracteres
|
|
no permitidos por la convención de nombres de PHP (es decir, el guión)
|
|
puede realizarse encapsulando el nombre del elemento con
|
|
corchetes y comillas.
|
|
</simpara>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
|
|
$json = '{"foo-bar": 12345}';
|
|
|
|
$obj = json_decode($json);
|
|
print $obj->{'foo-bar'}; // 12345
|
|
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</example>
|
|
<example>
|
|
<title>Errores comunes al usar la función <function>json_decode</function></title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
|
|
// Las siguientes cadenas son válidas en JavaScript pero no en JSON
|
|
|
|
// El nombre y el valor deben estar rodeados de comillas dobles.
|
|
// Las comillas simples no son válidas.
|
|
$bad_json = "{ 'bar': 'baz' }";
|
|
json_decode($bad_json); // null
|
|
|
|
// El nombre debe estar rodeado de comillas dobles.
|
|
$bad_json = '{ bar: "baz" }';
|
|
json_decode($bad_json); // null
|
|
|
|
// La coma final no está permitida.
|
|
$bad_json = '{ bar: "baz", }';
|
|
json_decode($bad_json); // null
|
|
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
</example>
|
|
<example>
|
|
<title>Errores con el parámetro <parameter>depth</parameter></title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
// Codificación de datos con un nivel máximo de anidamiento de 4 (array -> array -> array -> string)
|
|
$json = json_encode(
|
|
array(
|
|
1 => array(
|
|
'English' => array(
|
|
'One',
|
|
'January'
|
|
),
|
|
'French' => array(
|
|
'Une',
|
|
'Janvier'
|
|
)
|
|
)
|
|
)
|
|
);
|
|
|
|
// Definición de errores
|
|
$constants = get_defined_constants(true);
|
|
$json_errors = array();
|
|
foreach ($constants["json"] as $name => $value) {
|
|
if (!strncmp($name, "JSON_ERROR_", 11)) {
|
|
$json_errors[$value] = $name;
|
|
}
|
|
}
|
|
|
|
$json = json_encode(
|
|
array(
|
|
1 => array(
|
|
'English' => array(
|
|
'One',
|
|
'January'
|
|
),
|
|
'French' => array(
|
|
'Une',
|
|
'Janvier'
|
|
)
|
|
)
|
|
)
|
|
);
|
|
|
|
// Mostrar errores para diferentes niveles de anidamiento.
|
|
var_dump(json_decode($json, true, 4));
|
|
echo 'Last error: ', json_last_error_msg(), PHP_EOL, PHP_EOL;
|
|
|
|
var_dump(json_decode($json, true, 3));
|
|
echo 'Last error: ', json_last_error_msg(), PHP_EOL, PHP_EOL;
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
&example.outputs;
|
|
<screen>
|
|
<![CDATA[
|
|
array(1) {
|
|
[1]=>
|
|
array(2) {
|
|
["English"]=>
|
|
array(2) {
|
|
[0]=>
|
|
string(3) "One"
|
|
[1]=>
|
|
string(7) "January"
|
|
}
|
|
["French"]=>
|
|
array(2) {
|
|
[0]=>
|
|
string(3) "Une"
|
|
[1]=>
|
|
string(7) "Janvier"
|
|
}
|
|
}
|
|
}
|
|
Last error: No error
|
|
|
|
NULL
|
|
Last error: Maximum stack depth exceeded
|
|
]]>
|
|
</screen>
|
|
</example>
|
|
<example>
|
|
<title>Ejemplo con <function>json_decode</function> y grandes enteros</title>
|
|
<programlisting role="php">
|
|
<![CDATA[
|
|
<?php
|
|
$json = '{"number": 12345678901234567890}';
|
|
|
|
var_dump(json_decode($json));
|
|
var_dump(json_decode($json, false, 512, JSON_BIGINT_AS_STRING));
|
|
|
|
?>
|
|
]]>
|
|
</programlisting>
|
|
&example.outputs;
|
|
<screen>
|
|
<![CDATA[
|
|
object(stdClass)#1 (1) {
|
|
["number"]=>
|
|
float(1.2345678901235E+19)
|
|
}
|
|
object(stdClass)#1 (1) {
|
|
["number"]=>
|
|
string(20) "12345678901234567890"
|
|
}
|
|
]]>
|
|
</screen>
|
|
</example>
|
|
</para>
|
|
</refsect1>
|
|
|
|
<refsect1 role="notes">
|
|
&reftitle.notes;
|
|
<note>
|
|
<para>
|
|
La especificación JSON no forma parte de Javascript
|
|
sino de un subproyecto de Javascript.
|
|
</para>
|
|
</note>
|
|
<note>
|
|
<para>
|
|
Si ocurre un error durante la decodificación, la función
|
|
<function>json_last_error</function>
|
|
(o <function>json_last_error_msg</function> con PHP5.5+)
|
|
podrá ser utilizada para
|
|
determinar la naturaleza exacta del error.
|
|
</para>
|
|
</note>
|
|
</refsect1>
|
|
|
|
<refsect1 role="seealso">
|
|
&reftitle.seealso;
|
|
<para>
|
|
<simplelist>
|
|
<member><function>json_encode</function></member>
|
|
<member><function>json_last_error</function></member>
|
|
<member><function>json_last_error_msg</function></member>
|
|
</simplelist>
|
|
</para>
|
|
</refsect1>
|
|
</refentry>
|
|
|
|
<!-- Keep this comment at the end of the file
|
|
Local variables:
|
|
mode: sgml
|
|
sgml-omittag:t
|
|
sgml-shorttag:t
|
|
sgml-minimize-attributes:nil
|
|
sgml-always-quote-attributes:t
|
|
sgml-indent-step:1
|
|
sgml-indent-data:t
|
|
indent-tabs-mode:nil
|
|
sgml-parent-document:nil
|
|
sgml-default-dtd-file:"~/.phpdoc/manual.ced"
|
|
sgml-exposed-tags:nil
|
|
sgml-local-catalogs:nil
|
|
sgml-local-ecat-files:nil
|
|
End:
|
|
vim600: syn=xml fen fdm=syntax fdl=2 si
|
|
vim: et tw=78 syn=sgml
|
|
vi: ts=1 sw=1
|
|
-->
|