From cb9e359a51c3249d8f5157db69d43fd413ddeda6 Mon Sep 17 00:00:00 2001 From: Florian Merz Date: Thu, 11 Feb 2021 14:45:12 +0100 Subject: unslug ca: move --- .../reference/global_objects/json/index.html | 242 +++++++++++++++++++++ 1 file changed, 242 insertions(+) create mode 100644 files/ca/web/javascript/reference/global_objects/json/index.html (limited to 'files/ca/web/javascript/reference/global_objects/json/index.html') diff --git a/files/ca/web/javascript/reference/global_objects/json/index.html b/files/ca/web/javascript/reference/global_objects/json/index.html new file mode 100644 index 0000000000..efc86409e6 --- /dev/null +++ b/files/ca/web/javascript/reference/global_objects/json/index.html @@ -0,0 +1,242 @@ +--- +title: JSON +slug: Web/JavaScript/Referencia/Objectes_globals/JSON +translation_of: Web/JavaScript/Reference/Global_Objects/JSON +--- +
{{JSRef("Global_Objects", "JSON")}}
+ +

Resum

+ +

L'objecte JSON conté mètodes per a interpretar JavaScript Object Notation ({{glossary("JSON")}}) i convertir valors a JSON. Aquest objecte no pot ser cridat o construit, i a banda dels seus dos mètodes no té cap més funcionalitat o interès.

+ +

and converting values to JSON. It can't be called or constructed, and aside from its two method properties it has no interesting functionality of its own.

+ +

Descripció

+ +

JavaScript Object Notation

+ +

JSON és una sintaxi que permet serialitzar objectes, arrays, nombres, strings, booleans i {{jsxref("null")}}. Està basada en la sintaxi de JavaScript però és diferent: algunes parts de JavaScript no són convertibles a JSON i algunes de JSON no ho són a JavaScript. Vegeu també JSON: El subconjunt de JavaScript que no ho és.

+ + + + + + + + + + + + + + + + + + + + + + + +
Diferències entre JavaScript i JSON
Tipus a JavaScriptDiferències a JSON
Objectes i ArraysEls noms de les propietats han de estar embolcallats per cometes dobles; les cometes simples estan prohibides
NombresNo són permesos zeros a l'esquerra; els nombres decimals separent la part sencera amb un punt i han de tindre al menys un digit decimal.
Strings +

Només es pot escapar un grup limitat de caràcters; alguns caràcters de control no són permesos; el separador de línies Unicode (U+2028) i el separador de paràgrafs (U+2029) són permesos; les strings han d'estar embolcallades per cometes dobles. Vegeu l'exemple següent on {{jsxref("JSON.parse()")}} funciona correctament i es llença un {{jsxref("SyntaxError")}} a l'avaluar el codi com a JavaScript:

+ +
+var code = '"\u2028\u2029"';
+JSON.parse(code); // funciona correctament
+eval(code); // falla
+
+
+ +

La sintaxi completa de JSON és la següent:

+ +
JSON = null
+    o true o false
+    o JSONNumber
+    o JSONString
+    o JSONObject
+    o JSONArray
+
+JSONNumber = - PositiveNumber
+          o PositiveNumber
+PositiveNumber = DecimalNumber
+              o DecimalNumber . Digits
+              o DecimalNumber . Digits ExponentPart
+              o DecimalNumber ExponentPart
+DecimalNumber = 0
+             o OneToNine Digits
+ExponentPart = e Exponent
+            o E Exponent
+Exponent = Digits
+        o + Digits
+        o - Digits
+Digits = Digit
+      o Digits Digit
+Digit = 0 through 9
+OneToNine = 1 through 9
+
+JSONString = ""
+          o " StringCharacters "
+StringCharacters = StringCharacter
+                o StringCharacters StringCharacter
+StringCharacter = qualsevol caràcter excepte
+                  " o \ o U+0000 fins a U+001F
+               o EscapeSequence
+EscapeSequence = \" o \/ o \\ o \b o \f o \n o \r o \t
+              o \u HexDigit HexDigit HexDigit HexDigit
+HexDigit = 0 fins a 9
+        o A fins a F
+        o a fins a f
+
+JSONObject = { }
+          o { Members }
+Members = JSONString : JSON
+       o Members , JSONString : JSON
+
+JSONArray = [ ]
+         o [ ArrayElements ]
+ArrayElements = JSON
+             o ArrayElements , JSON
+
+ +

Pot haver-hi espais en blanc sense significat a qualsevol lloc excepte dins un JSONNumber (el nombres no poden contenir espais) o JSONString (on s'interpreta com el caràcter corrsponen dins l'string, o causaria un error). Els caràcters tabulador (U+0009), retorn de carro (U+000D), nova línia (U+000A), i l'espai (U+0020) són els únics caràcters d'espai en blanc acceptats.

+ +

Mètodes

+ +
+
{{jsxref("JSON.parse()")}}
+
Interpreta una string com a JSON, opcionalment transforma el valor produït i les seves propietats, i retorna el valor.
+
{{jsxref("JSON.stringify()")}}
+
Retorna un JSON string corresponent al valor especificat, opcionalment només inclou determinades propietats o reemplaça el valor de propietats tal i com defineixi l'usuari.
+
+ +

Polyfill

+ +

L'objecte JSON no és suportat a navegadors antics. Aquest problema pot solventar-se insertant el codi següent al principi dels scripts, permetent l'ús de l'objecte JSON en implementacions on no hi ha suport natiu (com ara Internet Explorer 6).

+ +

El següent algorisme emula l'objecte JSON natiu:

+ +
if (!window.JSON) {
+  window.JSON = {
+    parse: function(sJSON) { return eval('(' + sJSON + ')'); },
+    stringify: (function () {
+      var toString = Object.prototype.toString;
+      var isArray = Array.isArray || function (a) { return toString.call(a) === '[object Array]'; };
+      var escMap = {'"': '\\"', '\\': '\\\\', '\b': '\\b', '\f': '\\f', '\n': '\\n', '\r': '\\r', '\t': '\\t'};
+      var escFunc = function (m) { return escMap[m] || '\\u' + (m.charCodeAt(0) + 0x10000).toString(16).substr(1); };
+      var escRE = /[\\"\u0000-\u001F\u2028\u2029]/g;
+      return function stringify(value) {
+        if (value == null) {
+          return 'null';
+        } else if (typeof value === 'number') {
+          return isFinite(value) ? value.toString() : 'null';
+        } else if (typeof value === 'boolean') {
+          return value.toString();
+        } else if (typeof value === 'object') {
+          if (typeof value.toJSON === 'function') {
+            return stringify(value.toJSON());
+          } else if (isArray(value)) {
+            var res = '[';
+            for (var i = 0; i < value.length; i++)
+              res += (i ? ', ' : '') + stringify(value[i]);
+            return res + ']';
+          } else if (toString.call(value) === '[object Object]') {
+            var tmp = [];
+            for (var k in value) {
+              if (value.hasOwnProperty(k))
+                tmp.push(stringify(k) + ': ' + stringify(value[k]));
+            }
+            return '{' + tmp.join(', ') + '}';
+          }
+        }
+        return '"' + value.toString().replace(escRE, escFunc) + '"';
+      };
+    })()
+  };
+}
+
+ +

Dos polyfills complexos coneguts per a l'objecte JSON són JSON2 i JSON3.

+ +

Especificacions

+ + + + + + + + + + + + + + + + + + + +
EspecificacióEstatComentaris
{{SpecName('ES5.1', '#sec-15.12', 'JSON')}}{{Spec2('ES5.1')}} 
{{SpecName('ES6', '#sec-json-object', 'JSON')}}{{Spec2('ES6')}} 
+ +

Compatibilitat amb navegadors

+ +
{{CompatibilityTable}}
+ +
+ + + + + + + + + + + + + + + + + + + +
CaracterísticaChromeFirefox (Gecko)Internet ExplorerOperaSafari
Suport bàsic{{CompatVersionUnknown}}{{CompatGeckoDesktop("1.9.1")}}{{CompatIE("8.0")}}{{CompatOpera("10.5")}}{{CompatSafari("4.0")}}
+
+ +
+ + + + + + + + + + + + + + + + + + + + + +
CaracterísticaAndroidChrome for AndroidFirefox Mobile (Gecko)IE MobileOpera MobileSafari Mobile
Suport bàsic{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatGeckoMobile("1.0")}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}{{CompatVersionUnknown}}
+
+ +

Basat en la taula de compatibilitat de Kangax.

+ +

Vegeu també

+ + -- cgit v1.2.3-54-g00ecf