【问题标题】:Is it possible to do expressions/calculations in json?是否可以在 json 中进行表达式/计算?
【发布时间】:2019-05-21 01:45:47
【问题描述】:

我正在使用出色的 json-server 作为我的应用程序的后端,它对于点击自定义端点来检索一些数据非常有用。但是,如果它允许我进行计算/表达以便我也可以模仿后端行为,那将是超级有用的。

以这个数据结构为例

{
  "products": [
    {
      "name": "football",
      "id": "SPO-001",
      "category": "sport",
      "price": 40,
      "couponApplied": "false",
      "coupons": [
        "daw124qdw",
        "a1212cxn"
      ]
    }
  ]
}

我想要一些类似"discountPrice": couponApplied ? price * couponDiscount的说法

这只是我的伪编码。但我想做一些可以即时计算价格的事情。或者当我提出请求时,它会进行计算并返回计算数据(就像后端应用程序一样)

我知道我可以提出请求、应用优惠券并提供新价格。甚至提出发布请求并更改价格。但这都是在客户端完成的。有没有办法用 json 或 json-server 或任何其他解决方案来做到这一点。有道理吗?

【问题讨论】:

  • json-server 不是超级可定制的,所以我建议构建一个简单的express 服务器来满足您的需求。然后你可以模拟任何你想要的后端功能。
  • 然后我必须自己构建后端? @Galupuf
  • 是的。在我看来,您需要一个更自定义的解决方案。请记住,构建一个 express 应用程序来模拟数据非常简单。看看这个例子:expressjs.com/en/starter/hello-world.html 你需要做的就是添加你的自定义数据结构,然后你就可以了。
  • 不,出于同样的原因,我们不能在所有等效语言中都有这种东西:XML、YAML、csv……它们旨在澄清数据,而不是程序甚至公式跨度>
  • 请注意,json-server 是基于 express 和 allows you to use custom middleware 构建的,因此您应该能够使用简单的中间件函数进行转换。

标签: javascript json reactjs json-server


【解决方案1】:

JSON 表示JavaScript Object Notation,是数据结构,没有任何预处理器。您可以使用任何 JSON 解析器并动态附加/更改所需的值。

简而言之:不,不可能添加动态值

【讨论】:

  • 是的。它是严格的符号和格式化数据的一种方式。
  • 我的问题有什么解决办法吗?其他人必须对这种实际上不需要构建后端的后端“模拟”有需求?
【解决方案2】:

不,您将无法在 json 中进行计算。数据需要在别处变异然后发送。

【讨论】:

    【解决方案3】:

    不,不可能在 JSON 中进行数学运算或任何类型的表达式,因为 JSON 只是一种数据结构格式,而不是一种编程语言。

    您需要使用您选择的编程语言加载 JSON 数据,然后您可以对其进行操作。

    例如,既然你提到了javascript一个简单的Node程序作为例子..

    //It would be better to use the FileSystem API, but for simplicity for this example, I'm using require
    var json = require('./myjson.json'); 
    var product = json.products[0];
    
    //Since the dataset has "false", this if will handle both "false" (string) and false (boolean) values. The value should really be boolean if possible
    product.discountPrice = product.couponApplied && product.couponApplied !== "false" ? product.price * couponDiscount : null;
    

    【讨论】:

      【解决方案4】:

      如果您尝试动态创建逻辑,例如用户创建了一些逻辑,并且您希望将其保存到数据库中并稍后将其应用到某个地方,这些可能会有用:

      在您的示例中,使用公式解析器可能类似于:

      const response = {
        "products": [
          {
            "name": "football",
            "id": "SPO-001",
            "category": "sport",
            "price": 40,
            "couponApplied": "false",
            "coupons": [
              "daw124qdw",
              "a1212cxn"
            ]
          },
          {
            "name": "football",
            "id": "SPO-001",
            "category": "sport",
            "price": 40,
            "couponApplied": "true",
            "couponDiscount": 0.2,
            "coupons": [
              "daw124qdw",
              "a1212cxn"
            ]
          }
        ],
        formulaFields: {
          "discountPrice": 'IF("{couponApplied}"="true", {price} * {couponDiscount}, "")', // excel standard formula, with {variable} as product field keys
        }
      }
      
      const productsWithValues = response.products.map((product)=>{
        const productWithValues = { ...product };
        for (const field in response.formulaFields){
          const formula = response.formulaFields[field].replace(/\{([^\}]+)\}/g, (_, key) => product[key])
          const parser = new Parser();
          const { result } = parser.parse(formula);
          productWithValues[field] = result;
        }
        return productWithValues;
      })
      console.log(productsWithValues)
      

      输出:

      [
        {
          "name": "football",
          "id": "SPO-001",
          "category": "sport",
          "price": 40,
          "couponApplied": "false",
          "coupons": ["daw124qdw", "a1212cxn"],
          "discountPrice": null
        },
        {
          "name": "football",
          "id": "SPO-001",
          "category": "sport",
          "price": 40,
          "couponApplied": "true",
          "couponDiscount": 0.2,
          "coupons": ["daw124qdw", "a1212cxn"],
          "discountPrice": 8
        }
      ]
      

      【讨论】:

        【解决方案5】:

        JSON 不支持这个,但是如果你把它变成一个 Javascript 对象,你可以这样做:

        var obj = JSON.parse(
        `{
          "products": [
            {
              "name": "football",
              "id": "SPO-001",
              "category": "sport",
              "price": 40,
              "couponApplied": "true",
              "couponDiscount": 0.5,
              "coupons": [
                "daw124qdw",
                "a1212cxn"
              ]
            }
          ]
        }`).products[0];
        
        Object.defineProperty(obj,"discountPrice",{
          get:function(){
            return (this.couponApplied==="true"||this.couponApplied===true) ? this.price*this.couponDiscount : this.price;
          },
          set:function(){
            return;
          }
        });
        
        console.log(obj.discountPrice);

        这使用访问器描述符来定义依赖于其他对象属性值的对象属性。

        【讨论】:

          【解决方案6】:

          请注意,json-server 允许您使用 add custom middleware。所以你可以这样写:

          const updateProduct = (p) => ({
            ...p,
            discountPrice: p.couponApplied ? p.price * p.couponDiscount : p.price
          })
          
          const transform = ({products, ...rest}) => ({
            ...rest, 
            products: products.map(updateProduct)
          })
          
          const modify = (req, res, next) => {
            if (req.path !== '/my-route') return next();
          
            res.body = JSON.stringify(transform(JSON.parse(res.body)))
            next();
          }
          
          
          // dummy call -- would really be handled by json-server/express
          
          (() => {
            const req = {path: '/my-route'};
            const res = {body: `{"products":[{"name":"football","id":"SPO-001","category":"sport","price":40,"couponApplied":false,"coupons":["daw124qdw","a1212cxn"]},{"name":"helmet","id":"SPO-042","category":"sport","price":50,"couponApplied":true,"couponDiscount":0.75,"coupons":["foobarbaz"]}]}`}
            const next = () => {console.log(JSON.parse(res.body))}
            
            modify(req, res, next)
          })()

          【讨论】:

          • 抱歉这个愚蠢的问题,但这段代码在哪里?
          • 我不知道 json-server,但他们在 README 中有相关说明。
          猜你喜欢
          • 2018-06-22
          • 1970-01-01
          • 1970-01-01
          • 2021-10-10
          • 2015-05-30
          • 1970-01-01
          • 2021-12-02
          • 2011-09-23
          • 1970-01-01
          相关资源
          最近更新 更多