Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to do expressions/calculations in json?

I am using the wonderful json-server as the backend of my application and it's really useful for hitting custom endpoints to retrieve some data. but what would be super useful if it allowed me to do calculations/expression so that i can mimic that backend behaviour too.

take this data structure for example

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

I would like some way of saying something like "discountPrice": couponApplied ? price * couponDiscount

that's just me pseudo coding. but I would like to do something where I can calculate the price on the fly. or when I make a request it does a calculation and returns me the calculated data (like a backend app would)

I understand I can make a request, apply the coupon and render that new price. or even make a post request and change the price. but that is all done client side. is there any way to do this either with json or json-server or any other solutions. if that makes sense?

like image 351
Red Baron Avatar asked Dec 20 '18 14:12

Red Baron


People also ask

Can you pass a function in JSON?

Yes, you can.

Should JSON have quotes?

JavaScript object literals do not require quotes around a key name if the key is a valid identifier and not a reserved word. However, JSON always requires quotes around key names.


2 Answers

JSON means JavaScript Object Notation and is data structure, and does not have any preprocessor for it. You can use any JSON parser and append/change values that you need dynamically.

So in short: no, there is no possibility to add dynamic values

like image 177
Justinas Avatar answered Sep 23 '22 19:09

Justinas


No, you'll not be able to do computations inside json. The data would need to be mutated elsewhere and then sent.

like image 36
Josh Kelly Avatar answered Sep 21 '22 19:09

Josh Kelly