zoukankan      html  css  js  c++  java
  • JSON Stringification

    The JSON.stringify(..) utility will automatically omit undefined, function, and symbol values when it comes across them. If such a value is found in an array, that value is replaced by null (so that the array position information isn't altered). If found as a property of an object, that property will simply be excluded.

    JSON.stringify( undefined );					// undefined
    JSON.stringify( function(){} );					// undefined
    
    JSON.stringify( [1,undefined,function(){},4] );	// "[1,null,null,4]"
    JSON.stringify( { a:2, b:function(){} } );		// "{"a":2}"
    
    

    But if you try to JSON.stringify(..) an object with circular reference(s) in it, an error will be thrown.

    JSON stringification has the special behavior that if an object value has a toJSON() method defined, this method will be called first to get a value to use for serialization.

    If you intend to JSON stringify an object that may contain illegal JSON value(s), or if you just have values in the object that aren't appropriate for the serialization, you should define a toJSON() method for it that returns a JSON-safe version of the object.

    For example:

    var o = { };
    
    var a = {
    	b: 42,
    	c: o,
    	d: function(){}
    };
    
    // create a circular reference inside `a`
    o.e = a;
    
    // would throw an error on the circular reference
    // JSON.stringify( a );
    
    // define a custom JSON value serialization
    a.toJSON = function() {
    	// only include the `b` property for serialization
    	return { b: this.b };
    };
    
    JSON.stringify( a ); // "{"b":42}"
    

    It's a very common misconception that toJSON() should return a JSON stringification representation. That's probably incorrect, unless you're wanting to actually stringify the string itself (usually not!). toJSON() should return the actual regular value (of whatever type) that's appropriate, and JSON.stringify(..) itself will handle the stringification.

    In other words, toJSON() should be interpreted as "to a JSON-safe value suitable for stringification," not "to a JSON string" as many developers mistakenly assume.

  • 相关阅读:
    正向代理和反向代理的区别和作用
    idea 2018版/2019版的破解
    vue 开发环境的搭建
    shell 脚本操作informix数据库
    linux 系统文件目录颜色及特殊权限对应的颜色
    Linux系统结构详解(转)
    Java中的I/O流全汇总,所有的I/O就一张图
    安装Maven后使用cmd 执行 mvn -version命令 报错JAVA_HOME should point to a JDK not a JRE
    JavaWeb开发使用jsp还是html做前端页面
    lin-cms-dotnetcore.是如何方法级别的权限控制的?
  • 原文地址:https://www.cnblogs.com/zlv2snote/p/10754715.html
Copyright © 2011-2022 走看看