1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
|
---
title: JSON.parse()
slug: Web/JavaScript/Reference/Global_Objects/JSON/parse
tags:
- ECMAScript5
- JSON
- JavaScript
- Referencia
- metodo
translation_of: Web/JavaScript/Reference/Global_Objects/JSON/parse
original_slug: Web/JavaScript/Referencia/Objetos_globales/JSON/parse
---
<div>{{JSRef("Global_Objects", "JSON")}}</div>
<h2 id="Summary" name="Summary">Resumen</h2>
<p>El método <code><strong>JSON.parse()</strong></code> analiza una cadena de texto como JSON, transformando opcionalmente el valor producido por el análisis.</p>
<h2 id="Syntax" name="Syntax">Sintaxis</h2>
<pre class="syntaxbox"><code>JSON.parse(<em>text</em>[, <em>reviver</em>])</code></pre>
<h3 id="Parameters" name="Parameters">Parámetros</h3>
<dl>
<dt><code>text</code></dt>
<dd>El texto que se convertirá a JSON. Vea el objeto {{jsxref("JSON")}} para una descripción de la sintaxis JSON.</dd>
<dt><code>reviver</code> {{optional_inline()}}</dt>
<dd>Si una función, <span id="result_box" lang="es"><span class="hps">prescribe</span> <span class="hps">cómo se transforma</span> <span class="hps">el valor producido</span> <span class="hps">originalmente por</span> <span class="hps">el parsing</span></span>, antes de retornar.</dd>
</dl>
<h3 id="Returns">Returns</h3>
<p>Retorna el objeto que se corresponde con el texto JSON entregado.</p>
<h3 id="Exceptions">Exceptions</h3>
<p>Lanza una excepción {{jsxref("SyntaxError")}} si la cadena a transformar no es un JSON válido.</p>
<h2 id="Ejemplos">Ejemplos</h2>
<h3 id="Ejemplo_Usando_JSON.parse()">Ejemplo: Usando <code>JSON.parse()</code></h3>
<pre class="brush: js">JSON.parse('{}'); // {}
JSON.parse('true'); // true
JSON.parse('"foo"'); // "foo"
JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('null'); // null
</pre>
<h3 id="Ejemplo_Usando_el_parámetro_reviver">Ejemplo: <code>Usando el parámetro reviver</code></h3>
<p>Si se especifica un reviver, el valor computado por el parsing <em>es transformado </em>antes de retornar. Específicamente, el valor computado, y todas sus propiedades (comenzando con las propiedades más anidadas y siguiendo al propio valor original), son individualmente ejecutados a través del <code>reviver</code>, el cual es llamado con el objeto que contiene la propiedad que está siendo procesada como <code>this</code> y con el nombre de la propiedad como cadena y el valor de la propiedad como argumentos. Si la función <code>reviver</code> retorna <code>undefined</code> (o no retorna algún valor, por ejemplo: si la ejecución cae el final de la función), la propiedad es eliminada del objeto. De otra manera, la propiedad es redefinidad para ser el valor de retorno.</p>
<p>El <code>reviver</code> es llamada último con la cadena vacía y el valor más alto <span class="short_text" id="result_box" lang="es"><span class="hps">para permitir</span> <span class="hps">la transformación</span> <span class="hps">del valor</span> <span class="hps">más alto</span></span>. <span class="short_text" id="result_box" lang="es"><span class="hps">Asegúrese de</span> <span class="hps">manejar este caso</span> <span class="hps">adecuadamente</span></span>, <span id="result_box" lang="es"><span class="hps">por lo general</span> <span class="hps">mediante la devolución del</span> <span class="hps">valor proporcionado</span></span>, o <code>JSON.parse</code> will retorna <code>undefined</code>.</p>
<pre class="brush: js">JSON.parse('{"p": 5}', function (k, v) {
if(k === "") return v; // if topmost value, return it,
return v * 2; // else return v * 2.
}); // { p: 10 }
JSON.parse('{"1": 1, "2": 2,"3": {"4": 4, "5": {"6": 6}}}', function (k, v) {
console.log(k); // log the current property name, the last is "".
return v; // return the unchanged property value.
});
// 1
// 2
// 4
// 6
// 5
// 3
// ""
</pre>
<h3 id="JSON.parse()_no_admite_comas_finales"><code>JSON.parse()</code> no admite comas finales</h3>
<pre class="example-bad brush: js example-bad line-numbers language-js"><code class="language-js"><span class="comment token">// ambos lanzarán un SyntaxError</span>
JSON<span class="punctuation token">.</span><span class="function token">parse</span><span class="punctuation token">(</span><span class="string token">'[1, 2, 3, 4, ]'</span><span class="punctuation token">)</span><span class="punctuation token">;</span>
JSON<span class="punctuation token">.</span><span class="function token">parse</span><span class="punctuation token">(</span><span class="string token">'{"foo" : 1, }'</span><span class="punctuation token">)</span><span class="punctuation token">;</span></code></pre>
<h2 id="Especificaciones">Especificaciones</h2>
<table class="standard-table">
<tbody>
<tr>
<th scope="col">Especificación</th>
<th scope="col">Estado</th>
<th scope="col">Comentario</th>
</tr>
<tr>
<td>{{SpecName('ES5.1', '#sec-15.12.2', 'JSON.parse')}}</td>
<td>{{Spec2('ES5.1')}}</td>
<td>Definición inicial.<br>
Implementado en JavaScript 1.7.</td>
</tr>
<tr>
<td>{{SpecName('ES6', '#sec-json.parse', 'JSON.parse')}}</td>
<td>{{Spec2('ES6')}}</td>
<td>
<p> </p>
</td>
</tr>
<tr>
<td>{{SpecName('ESDraft', '#sec-json.parse', 'JSON.parse')}}</td>
<td>{{Spec2('ESDraft')}}</td>
<td> </td>
</tr>
</tbody>
</table>
<h2 id="Compatibilidad_de_navegadores">Compatibilidad de navegadores</h2>
<p>{{ CompatibilityTable() }}</p>
<div id="compat-desktop">
<table class="compat-table">
<tbody>
<tr>
<th>Característica</th>
<th>Chrome</th>
<th>Firefox (Gecko)</th>
<th>Internet Explorer</th>
<th>Opera</th>
<th>Safari</th>
</tr>
<tr>
<td>Soporte básico</td>
<td>{{ CompatVersionUnknown() }}</td>
<td>{{ CompatGeckoDesktop("1.9.1") }}</td>
<td>8.0</td>
<td>10.5</td>
<td>4.0</td>
</tr>
</tbody>
</table>
</div>
<div id="compat-mobile">
<table class="compat-table">
<tbody>
<tr>
<th>Característica</th>
<th>Android</th>
<th>Chrome para Android</th>
<th>Firefox Mobile (Gecko)</th>
<th>IE Mobile</th>
<th>Opera Mobile</th>
<th>Safari Mobile</th>
</tr>
<tr>
<td>Soporte básico</td>
<td>{{ CompatVersionUnknown() }}</td>
<td>{{ CompatVersionUnknown() }}</td>
<td>{{ CompatGeckoMobile("1.0") }}</td>
<td>{{ CompatVersionUnknown() }}</td>
<td>{{ CompatVersionUnknown() }}</td>
<td>{{ CompatVersionUnknown() }}</td>
</tr>
</tbody>
</table>
</div>
<p>Based on <a class="external" href="http://kangax.github.com/es5-compat-table/">Kangax's compat table</a>.</p>
<h3 id="Especificaciones_Gecko">Especificaciones Gecko</h3>
<p>Comenzando con Gecko 29 {{geckoRelease("29")}},<span class="short_text" id="result_box" lang="es"><span class="hps"> unas cadenas JSON malformadas</span></span><span class="short_text" lang="es"><span class="hps"> producen</span> </span><span id="result_box" lang="es"><span class="hps">un mensaje</span> <span class="hps">de error más detallado</span> <span class="hps">que contiene el</span> <span class="hps">número de línea y</span> <span class="hps">columna</span> <span class="hps">que provocó el</span> <span class="hps">error de parsing</span></span>. Esto es útil cuando se está haciendo debug de un JSON grande.</p>
<pre class="brush: js">JSON.parse('[1, 2, 3,]')
// SyntaxError: JSON.parse: unexpected character at
// line 1 column 10 of the JSON data
</pre>
<h2 id="Véase_también">Véase también</h2>
<ul>
<li><a href="/en-US/docs/Web/JavaScript/Guide/Using_native_JSON">Utilizando</a> <a href="/en-US/docs/Web/JavaScript/Guide/Using_native_JSON">JSON nativo</a></li>
</ul>
|