★ wanayoo — archive 1999 https://developer.mozilla.org/ca/docs/Web/JavaScript/Referencia/Objectes_globals/JSONNouvelle recherche | Portail wanayoo
mozilla
Your Search Results

    JSON

    This article is in need of an editorial review.

    Resum

    L'objecte JSON conté mètodes per a interpretar JavaScript Object Notation (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 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 JavaScript Diferències a JSON
    Objectes i Arrays Els noms de les propietats han de estar embolcallats per cometes dobles; les cometes simples estan prohibides
    Nombres No 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 JSON.parse() funciona correctament i es llença un 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

    JSON.parse()
    Interpreta una string com a JSON, opcionalment transforma el valor produït i les seves propietats, i retorna el valor.
    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ó Estat Comentaris
    ECMAScript 5.1 (ECMA-262)
    The definition of 'JSON' in that specification.
    Standard  
    ECMAScript 6 (ECMA-262)
    The definition of 'JSON' in that specification.
    Release Candidate  

    Compatibilitat amb navegadors

    Característica Chrome Firefox (Gecko) Internet Explorer Opera Safari
    Suport bàsic (Yes) 3.5 (1.9.1) 8.0 10.5 4.0
    Característica Android Chrome for Android Firefox Mobile (Gecko) IE Mobile Opera Mobile Safari Mobile
    Suport bàsic (Yes) (Yes) 1.0 (1.0) (Yes) (Yes) (Yes)

    Basat en la taula de compatibilitat de Kangax.

    Vegeu també

    Document Tags and Contributors

    Contributors to this page: enTropy, teoli
    Last updated by: teoli,