NodeJS项目中Jsonata模块的用法

时间:2018-11-29 09:02:02

标签: javascript

我尝试过jsonata运动器。看起来很酷。

但是我必须在我的代码(NodeJS)中实现它。

输入为:

{
  "id": "course_uuid1",
  "description": "Sample course description",
  "contentType": "COURSE",
  "category": "Course",
  "durationInSeconds": 500,
  "expertiseLevels": ["INTERMEDIATE"],
  "imageUrl": "https://percipio.com/courseuuid1/imagelink",
  "link": "https://percipio.com/courseuuid1",
  "modalities": ["LISTEN", "READ", "WATCH"],
  "languageCode": "en",
  "parent": null,
  "publishDate": "2018-11-19T10:23:34Z",
  "sourceName": null,
  "technologyTitle": null,
  "technologyVersion": null,
  "title": "Java",
  "by": ["admin"]
}

转换逻辑为:

{
  "pkID": id,
  "description": description,
  "componentTypeID": contentType,
  "totalLength": durationInSeconds,
  "thumbnailURI": imageUrl,
  "locale": languageCode,
  "createTimestamp": publishDate,
  "title": title,
  "lastUpdateUser": by
}

我希望以转换逻辑格式输出,但要通过NODEJS代码输出。

请提出建议

2 个答案:

答案 0 :(得分:1)

安装 jsonata 节点模块,然后尝试以下代码:

var jsonata = require('jsonata');
    let input=
    {
      "id": "course_uuid1",
      "description": "Sample course description",
      "contentType": "COURSE",
      "category": "Course",
      "durationInSeconds": 500,
      "expertiseLevels": ["INTERMEDIATE"],
      "imageUrl": "https://percipio.com/courseuuid1/imagelink",
      "link": "https://percipio.com/courseuuid1",
      "modalities": ["LISTEN", "READ", "WATCH"],
      "languageCode": "en",
      "parent": null,
      "publishDate": "2018-11-19T10:23:34Z",
      "sourceName": null,
      "technologyTitle": null,
      "technologyVersion": null,
      "title": "Java",
      "by": ["admin"]
    }
    let exp="{'pkID': id,'description': description,'componentTypeID': contentType,'totalLength': durationInSeconds,'thumbnailURI': imageUrl,'locale': languageCode,'createTimestamp': publishDate,'title': title,'lastUpdateUser': by}";
    let expression = jsonata(exp);
    let expResult = expression.evaluate(input);
    console.log(expResult);

答案 1 :(得分:0)

我想这就是你想要的:

var inputJson={
  "id": "course_uuid1",
  "description": "Sample course description",
  "contentType": "COURSE",
  "category": "Course",
  "durationInSeconds": 500,
  "expertiseLevels": ["INTERMEDIATE"],
  "imageUrl": "https://percipio.com/courseuuid1/imagelink",
  "link": "https://percipio.com/courseuuid1",
  "modalities": ["LISTEN", "READ", "WATCH"],
  "languageCode": "en",
  "parent": null,
  "publishDate": "2018-11-19T10:23:34Z",
  "sourceName": null,
  "technologyTitle": null,
  "technologyVersion": null,
  "title": "Java",
  "by": ["admin"]
};

var outputJson={
  "pkID": inputJson.id,
  "description": inputJson.description,
  "componentTypeID": inputJson.contentType,
  "totalLength": inputJson.durationInSeconds,
  "thumbnailURI": inputJson.imageUrl,
  "locale": inputJson.languageCode,
  "createTimestamp": inputJson.publishDate,
  "title": inputJson.title,
  "lastUpdateUser": inputJson.by
}