JavaScript:从一种嵌套JSON格式转换为另一种嵌套JSON格式

如何解决JavaScript:从一种嵌套JSON格式转换为另一种嵌套JSON格式

我正在尝试将AVRO模式转换为ElasticSearch索引模板。两者都是JSON结构,在转换时需要检查一些内容。我尝试使用递归将所有嵌套元素取出,然后将它们与父母配对,但是在深入解析递归的同时写成字典使我不得不问这个问题。

所以基本上我有这个AVRO模式文件:

{
    "name": "animal","type": [
        "null",{
            "type": "record","name": "zooAnimals","fields": [{
                    "name": "color","type": ["null","string"],"default": null
                },{
                    "name": "skinType",{
                    "name": "species","type": {
                        "type": "record","name": "AnimalSpecies","fields": [{
                                "name": "terrestrial","type": "string"
                            },{
                                "name": "aquatic","type": "string"
                            }
                        ]
                    }
                },{
                    "name": "behavior","type": [
                        "null",{
                            "type": "record","name": "AnimalBehaviors","fields": [{
                                    "name": "sound","default": null
                                },{
                                    "name": "hunt","default": null
                                }
                            ]
                        }
                    ],"default": null
                }
            ]
        }
    ]
}

,我希望将其转换为这种(Elasticsearch索引模板格式):

{
    "properties": {
        "color" :{
            "type" : "keyword"
        },"skinType" :{
            "type" : "keyword"
        },"species" :{
            "properties" : {
                "terrestrial" : {
                    "type" : "keyword"
                },"aquatic" : {
                    "type" : "keyword"
                },}
           
        },"behavior" : {
            "properties" : {
                "sound" : {
                    "type" : "keyword"
                },"hunt" : {
                    "type" : "keyword"
                }
            }
        }
    }
}

重要说明:可以进一步嵌套在AVRO模式上的嵌套,这就是为什么我在考虑递归来解决的原因。同样,type的类型可以是ArrayMap,如behaviorspecies所示,其中行为具有数组,而种类具有地图。

如果您必须看到我做了反复试验,这是我的代码无法帮助我:

const checkDataTypeFromObject = function (obj) {

  if (Object.prototype.toString.call(obj) === "[object Array]") {
    obj.map(function (item) {
      if (Object.prototype.toString.call(item) === "[object Object]") {
        // so this is an object that could contain further nested fields
        dataType = item;
        mappings.properties[item.name] = { "type" : item.type}
         if (item.hasOwnProperty("fields")) {
          checkDataTypeFromObject(item.fields);
        } else if (item.hasOwnProperty("type")) {
          checkDataTypeFromObject(item.type);
        } 
      } else if (item === null) {
        // discard the nulls,nothing to do here
      } else {
        // if not dict or null,this is the dataType we are looking for
        dataType = item;
      }

      return item.name
    });

解决方法

我不知道您的输入格式也不知道您的输出格式。因此,这可能是不完整的。不过,它可以捕获您的示例案例,并且可以作为您可以在其中添加子句/条件的基线:

const convertField = ({name,type,fields}) =>
  Array .isArray (type) && type [0] === 'null' && type [1] === 'string'
    ? [name,{type: 'keyword'}]
  : Array .isArray (type) && type [0] === 'null' && Object (type [1]) === type [1]
    ? [name,{properties: Object .fromEntries (type [1] .fields .map (convertField))}]
  : Object (type) === type
    ? [name,{properties: Object .fromEntries (type .fields .map (convertField))}]
  : // else 
      [name,{type: 'keyword'}]

const convert = (obj) =>
  convertField (obj) [1]

const input = {name: "animal",type: ["null",{type: "record",name: "zooAnimals",fields: [{name: "color","string"],default: null},{name: "skinType",{name: "species",type: {type: "record",name: "AnimalSpecies",fields: [{name: "terrestrial",type: "string"},{name: "aquatic",type: "string"}]}},{name: "behavior",name: "AnimalBehaviors",fields: [{name: "sound",{name: "hunt",default: null}]}],default: null}]}]}

console .log (convert (input))
.as-console-wrapper {min-height: 100% !important; top: 0}

辅助函数convertField将输入的一个字段转换为[name,<something>]格式,其中<something>type属性的结构而变化。在两种情况下,我们使用这些结构的数组作为Object .fromEntries的输入,以创建对象。

主函数convert只是从根上调用convertField的结果中获取第二个属性。如果总体结构总是像本例中那样开始,那将起作用。

请注意,这两个子句(第一个和第四个)的结果是相同的,而其他两个则非常相似。同样,对第一和第二子句的测试也非常接近。因此,可能存在一些合理的方法可以简化此过程。但是,由于匹配测试与匹配输出的排列不太吻合,因此它可能并非微不足道。

您可以轻松地添加其他条件和结果。实际上,我最初是用最后两行写成的:

  : type === 'string'
    ? [name,{type: 'keyword'}]
  : // else 
      [name,{type: 'unknown'}]

可以更好地显示在何处添加其他子句,如果错过了个案,还可以在结果中添加符号(unknown

,

我们可以使用归纳推理将其分解。下面的编号点对应代码中的编号注释-

  1. 如果输入t为空,则返回一个空对象
  2. (归纳)t不为null。如果t.type是一个对象,则transform的每一片叶子加起来成为一个对象
  3. (归纳)t不为空,并且t.type不是对象。如果t.fields是一个对象,则将每个叶子transform分配给{ [name]: ... },并求和成一个 properties 对象
  4. (归纳)t不是null且t.type不是对象,并且t.fields不是对象。返回关键字
const transform = t =>
  t === "null"
    ? {}                           // <- 1
: isObject(t.type)
    ? arr(t.type)                  // <- 2
        .map(transform)
        .reduce(assign,{})
: isObject(t.fields)
    ? { propertries:               // <- 3
          arr(t.fields)
            .map(v => ({ [v.name]: transform(v) }))
            .reduce(assign,{})
      }
: { type: "keyword" }              // <- 4

有一些助手可以避免复杂性-

const assign = (t,u) =>
  Object.assign(t,u)

const arr = t =>
  Array.isArray(t) ? t : [t]
  
const isObject = t =>
  Object(t) === t

只需运行transform-

console.log(transform(input))

展开下面的代码片段,以在浏览器中验证结果-

const assign = (t,u)

const arr = t =>
  Array.isArray(t) ? t : [t]
  
const isObject = t =>
  Object(t) === t

const transform = t =>
  t === "null"
    ? {}
: isObject(t.type)
    ? arr(t.type)
        .map(transform)
        .reduce(assign,{})
: isObject(t.fields)
    ? { propertries:
          arr(t.fields)
            .map(v => ({ [v.name]: transform(v) }))
            .reduce(assign,{})
      }
: { type: "keyword" }

const input =
  {name: "animal",default: null}]}]}

console.log(transform(input))

输出-

{
  "propertries": {
    "color": {
      "type": "keyword"
    },"skinType": {
      "type": "keyword"
    },"species": {
      "propertries": {
        "terrestrial": {
          "type": "keyword"
        },"aquatic": {
          "type": "keyword"
        }
      }
    },"behavior": {
      "propertries": {
        "sound": {
          "type": "keyword"
        },"hunt": {
          "type": "keyword"
        }
      }
    }
  }
}

nota bene

步骤2 中,我们可以有一个复杂的type,例如-

{ name: "foo",type: [ "null",{ obj1 },{ obj2 },... ],...
}

在这种情况下,obj1obj2可能分别transform成为{ properties: ... }对象。使用.reduce(assign,{})意味着obj1的属性将被obj2的属性覆盖-

: isObject(t.type)
    ? arr(t.type)
        .map(transform)
        .reduce(assign,{})   // <- cannot simply use `assign`

为解决此问题,我们将步骤2更智能地更改为merge复杂类型-

: isObject(t.type)
    ? arr(t.type)
        .map(transform)
        .reduce(merge,{})   // <- define a more sophisticated merge

merge可能类似于-

const merge = (t,u) =>
  t.properties && u.properties // <- both
    ? { properties: Object.assign(t.properties,u.properties) }
: t.properties                 // <- only t
    ? { properties: Object.assign(t.properties,u) }
: u.properties                 // <- only u
    ? { properties: Object.assign(t,u.properties) }
: Object.assign(t,u)          // <- neither

或相同的merge,但使用不同的逻辑方法-

const merge = (t,u) =.
  t.properties || u.properties    // <- either
    ? { properties:               
          Object.assign
            ( t.properties || t,u.properties || u
            )
      }
    : Object.assign(t,u)         // <- neither

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐


依赖报错 idea导入项目后依赖报错,解决方案:https://blog.csdn.net/weixin_42420249/article/details/81191861 依赖版本报错:更换其他版本 无法下载依赖可参考:https://blog.csdn.net/weixin_42628809/a
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下 2021-12-03 13:33:33.927 ERROR 7228 [ main] o.s.b.d.LoggingFailureAnalysisReporter : *************************** APPL
错误1:gradle项目控制台输出为乱码 # 解决方案:https://blog.csdn.net/weixin_43501566/article/details/112482302 # 在gradle-wrapper.properties 添加以下内容 org.gradle.jvmargs=-Df
错误还原:在查询的过程中,传入的workType为0时,该条件不起作用 &lt;select id=&quot;xxx&quot;&gt; SELECT di.id, di.name, di.work_type, di.updated... &lt;where&gt; &lt;if test=&qu
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct redisServer’没有名为‘server_cpulist’的成员 redisSetCpuAffinity(server.server_cpulist); ^ server.c: 在函数‘hasActiveC
解决方案1 1、改项目中.idea/workspace.xml配置文件,增加dynamic.classpath参数 2、搜索PropertiesComponent,添加如下 &lt;property name=&quot;dynamic.classpath&quot; value=&quot;tru
删除根组件app.vue中的默认代码后报错:Module Error (from ./node_modules/eslint-loader/index.js): 解决方案:关闭ESlint代码检测,在项目根目录创建vue.config.js,在文件中添加 module.exports = { lin
查看spark默认的python版本 [root@master day27]# pyspark /home/software/spark-2.3.4-bin-hadoop2.7/conf/spark-env.sh: line 2: /usr/local/hadoop/bin/hadoop: No s
使用本地python环境可以成功执行 import pandas as pd import matplotlib.pyplot as plt # 设置字体 plt.rcParams[&#39;font.sans-serif&#39;] = [&#39;SimHei&#39;] # 能正确显示负号 p
错误1:Request method ‘DELETE‘ not supported 错误还原:controller层有一个接口,访问该接口时报错:Request method ‘DELETE‘ not supported 错误原因:没有接收到前端传入的参数,修改为如下 参考 错误2:cannot r
错误1:启动docker镜像时报错:Error response from daemon: driver failed programming external connectivity on endpoint quirky_allen 解决方法:重启docker -&gt; systemctl r
错误1:private field ‘xxx‘ is never assigned 按Altʾnter快捷键,选择第2项 参考:https://blog.csdn.net/shi_hong_fei_hei/article/details/88814070 错误2:启动时报错,不能找到主启动类 #
报错如下,通过源不能下载,最后警告pip需升级版本 Requirement already satisfied: pip in c:\users\ychen\appdata\local\programs\python\python310\lib\site-packages (22.0.4) Coll
错误1:maven打包报错 错误还原:使用maven打包项目时报错如下 [ERROR] Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:3.2.0:resources (default-resources)
错误1:服务调用时报错 服务消费者模块assess通过openFeign调用服务提供者模块hires 如下为服务提供者模块hires的控制层接口 @RestController @RequestMapping(&quot;/hires&quot;) public class FeignControl
错误1:运行项目后报如下错误 解决方案 报错2:Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:3.8.1:compile (default-compile) on project sb 解决方案:在pom.
参考 错误原因 过滤器或拦截器在生效时,redisTemplate还没有注入 解决方案:在注入容器时就生效 @Component //项目运行时就注入Spring容器 public class RedisBean { @Resource private RedisTemplate&lt;String
使用vite构建项目报错 C:\Users\ychen\work&gt;npm init @vitejs/app @vitejs/create-app is deprecated, use npm init vite instead C:\Users\ychen\AppData\Local\npm-