Home > Software design >  Trying a create a object using jsonata from existing object
Trying a create a object using jsonata from existing object

Time:10-17

Trying to create object out of existing object using jsonata. When the data and expression is put in jsonata excerciser, correct result is generated. However when I run it in Javascript program, errors are generated.

following is javascript code

const data = {
    "compCode": "0006",
    "compState": "MH",
    "recvDocNo": "0075",
    "buCode": "AC",
    "branchCode": "001",
    "recvLines": [
        {
            "lineNo": 1,
            "itemId": "00002",
            "qtyAccept": 10,
            "unitRate": 100,
            "basicVal": 1000,
            "taxableAmt": 1000,
        }
    ]
};

let expr = {
    "compCode": compCode,
    "buCode": buCode,
    "lineNo": recvLines.lineNo,
    "itemId": recvLines.itemId
};

jsonata(expr).evaluate(data);

I get error - ReferenceError: compCode is not defined

when I change it to data.compCode and all other object properties similarly, I get an error TypeError: path.charAt is not a function. Could someone tell me how to get it working. Thanks in advance

CodePudding user response:

It looks like jsonata() expects a string expression as a parameter, which isn't explicitly stated in the docs, but is shown in the In Nodejs section.

const data = {
    "compCode": "0006",
    "compState": "MH",
    "recvDocNo": "0075",
    "buCode": "AC",
    "branchCode": "001",
    "recvLines": [
        {
            "lineNo": 1,
            "itemId": "00002",
            "qtyAccept": 10,
            "unitRate": 100,
            "basicVal": 1000,
            "taxableAmt": 1000,
        },
         {
            "lineNo": 2,
            "itemId": "00006",
            "qtyAccept": 10,
            "unitRate": 100,
            "basicVal": 1000,
            "taxableAmt": 1000,
        }
    ]
};

let expr = `{
  "compCode": compCode, 
  "buCode": buCode, 
  "lineNo": recvLines.lineNo, 
  "itemId": recvLines.itemId
  }`;

console.log(jsonata(expr).evaluate(data));
<script src="https://cdn.jsdelivr.net/npm/[email protected]/jsonata.min.js"></script>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>

  • Related