JavaScript的對象與Json

來源:互聯網
上載者:User

標籤:symbol   方法   gif   images   pre   key   replace   ring   efi   

JSON有非常嚴格的文法,在string上下文裡{ "prop": "val" } 是個合法的JSON,但{ prop: "val" }和{ ‘prop‘: ‘val‘ }確實不合法的。所有屬性名稱和它的值都必須用雙引號引住,不能使用單引號。在string上下文裡使用帶有大括弧的JavaScript對象,那它就是JSON字串,而如果在對象字面量上下文裡使用的話,那它就是對象字面量。

JSON.stringify(true);                // ‘true‘

JSON.stringify(‘foo‘);               // ‘"foo"‘

JSON.stringify([1, ‘false‘, false]); // ‘[1,"false",false]‘

JSON.stringify({ x: 5 });            // ‘{"x":5}‘

 

JSON.stringify(new Date(2006, 0, 2, 15, 4, 5)) // ‘"2006-01-02T15:04:05.000Z"‘

 

JSON.stringify({ x: 5, y: 6 });// ‘{"x":5,"y":6}‘ or ‘{"y":6,"x":5}‘

JSON.stringify([new Number(1), new String(‘false‘), new Boolean(false)]);// ‘[1,"false",false]‘

 

JSON.stringify({ x: [10, undefined, function(){}, Symbol(‘‘)] }); // ‘{"x":[10,null,null,null]}‘

 // Symbols:

JSON.stringify({ x: undefined, y: Object, z: Symbol(‘‘) });// ‘{}‘

JSON.stringify({ [Symbol(‘foo‘)]: ‘foo‘ });// ‘{}‘

JSON.stringify({ [Symbol.for(‘foo‘)]: ‘foo‘ }, [Symbol.for(‘foo‘)]);// ‘{}‘

JSON.stringify({ [Symbol.for(‘foo‘)]: ‘foo‘ }, function(k, v) {

  if (typeof k === ‘symbol‘) {

    return ‘a symbol‘;

  }});// ‘{}‘

// Non-enumerable properties:

JSON.stringify( Object.create(null, { x: { value: ‘x‘, enumerable: false }, y: { value: ‘y‘, enumerable: true } }) );// ‘{"y":"y"}‘

function replacer(key, value) {

  // Filtering out properties

  if (typeof value === "string") {

    return undefined;

  }

  return value;}

var foo = {foundation: "Mozilla", model: "box", week: 45, transport: "car", month: 7};

JSON.stringify(foo, replacer);// ‘{"week":45,"month":7}‘

JSON.stringify(foo, [‘week‘, ‘month‘]);  // ‘{"week":45,"month":7}‘, only keep "week" and "month" properties

 

 

如果字串化對象有一個屬性叫tojson其值是一個函數,然後tojson()方法自訂JSON字串化所帶來的行為,而不是被序列化的對象,返回的值將被序列化tojson()方法調用時。例如

var obj = {

  foo: ‘foo‘,

  toJSON: function() {

    return ‘bar‘;

  }};

JSON.stringify(obj);        // ‘"bar"‘

JSON.stringify({ x: obj }); // ‘{"x":"bar"}‘

 

5: JSON.parse()

JSON.parse(‘{}‘);              // {}

JSON.parse(‘true‘);            // true

JSON.parse(‘"foo"‘);           // "foo"

JSON.parse(‘[1, 5, "false"]‘); // [1, 5, "false"]

JSON.parse(‘null‘);            // null

 

JavaScript的對象與Json

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.