JavaScript代码读取json输入并映射到json输出

时间:2018-07-26 14:17:05

标签: javascript apache-nifi

我有以下脚本,并在nifi设置中使用它,但想尽办法问与javascript本身有关的问题。我想阅读json输入并将其映射为特定的输出格式。 json本身可以包含不同的字段,因此它必须以通用方式读取json,然后根据输入字段映射到输出json。

var IOUtils = Java.type("org.apache.commons.io.IOUtils");
var StandardCharsets = Java.type("java.nio.charset.StandardCharsets");
var transformed_message = {};
var error = false;
var measurement = "test_measurement";
var sep = "\n"

// Get attributes
flowFile = session.write(flowFile, new StreamCallback(function 
   (inputStream, 
 outputStream) {
    // Read input FlowFile content
    var type = flowFile.getAttribute('type')
    var time = Number(flowFile.getAttribute('filename'))
    var meta_name = flowFile.getAttribute('meta_name')
    var remote_source_name = 
      flowFile.getAttribute('gethttp.remote.source')

    var content = IOUtils.toString(inputStream, StandardCharsets.UTF_8); 
    // 
     message or content
    var message_content = {};
    try {
        message_content = JSON.parse(content);
        transformed_message.state = (((message_content || {}).state || 
          "null"));
        transformed_message.new_records = (((message_content || 
           {}).new_records || 0));
        transformed_message.updated_records = (((message_content || 
           {}).updated_records || 0));
        transformed_message.changed_records = (((message_content || 
           {}).changed_records || 0));
        transformed_message.deleted_records = (((message_content || 
           {}).deleted_records || 0));
        transformed_message.missing_records = (((message_content || 
           {}).missing_records || 0));

          line = line + ",remote_source_name="+ remote_source_name + ",meta_name="+meta_name+",message_type=" + type + " " 
                 + "new_records=" + transformed_message.new_records + ","
                 + "updated_records=" + transformed_message.updated_records + ","
                 + "changed_records=" + transformed_message.changed_records + ","
                 + "deleted_records=" + transformed_message.deleted_records + ","
                 + "missing_records=" + transformed_message.missing_records + " "
                 + time * 1000000 + sep;


        // Write output content
        if (transformed_message) {
            outputStream.write(line.getBytes(StandardCharsets.UTF_8));
        }

因此在此脚本中,它读取json数组并解析已知的预期属性或字段。 javascript中是否有一种方法可以只读取所有字段或json对象,然后根据读取的输入字段的数量创建所需的json?我们可以暂时将类型保留为字符串,将格式保留为json对象,然后稍后添加代码以检查数组还是对象。希望这对我尝试做的事情有意义。

0 个答案:

没有答案