JS的JSON中为啥不能有if-else结构

你这个不是JSON,你这个是Ecma Object Type。Object的field只能是value或者accessor 【JS的JSON中为啥不能有if-else结构】 An Object is logically a collection of properties. Each property is either a data property, or an accessor property:
A data property associates a key value with an ECMAScript language value and a set of Boolean attributes.
An accessor property associates a key value with one or two accessor functions, and a set of Boolean attributes. The accessor functions are used to store or retrieve an ECMAScript language value that is associated with the property.
http://www.ecma-international.org/ecma-262/6.0/index.html#sec-object-type简单点说, 能放等号右边的才是value,带if的通通不是。你要真想弄个条件属性,可以:let val = truedata = https://www.zhihu.com/api/v4/questions/46432650/{ decidedByVal: (function(x){ if(x){ return"true" }else{ return "false" }})(val)}但是要注意,这个data被声明以后,decidedByVal就是\u0026#39;true\u0026#39;了,你改val也没用。要想弄个随val变化的,要用definePropertyObject.defineProperty(obj,\u0026#39;decidedByVal\u0026#39;,{ get: () =\u0026gt; { if(val) return \u0026#39;true\u0026#39; return \u0026#39;false\u0026#39; }, enumerable: true, configurable: false})另,你听谁说JSON可以这么写的……
■网友
json是js语法的一个子集,专门用来表示数据的,不能有逻辑没有function,没有undefined
■网友
1.你写的这三个玩意都不是json,在js里这叫对象,你后几个例子违反的是js中对对象的语法规定,跟json半毛钱关系也没有。2.至于说为啥json里不能有if,就好比你问为什么英语里说two apples,苹果要用复数,我用单数不行吗,不行,这是人家语法规定。
■网友
json不属于javascript参考我的这篇文章:彻底精通JSON
■网友
json是一个很小巧很稳定的数据载体格式
■网友
json是一种序列化编码
■网友
您的问题不是JSON而是JavaScript对象字面量。JavaScript对象字面量的语法,在花括号中的键值对的值的部分必需是一个表达式。if else结构不是表达式而是语句,所以不行
■网友
json 是一种数据格式。不是逻辑、运算表达式


    推荐阅读