<template>
  <div>
    <div/>
  </div>
</template>

<script>
export default {
  data() {
    return {
      arr: []
    }
  },
  mounted() {
    const obj = {
      code: 200,
      msg: 'success',
      data: {
        'acid': '123456'
      }
    }
    const arr = []
    this.jsonPath(arr, obj, '$')
    this.arr = arr
  },
  methods: {
    jsonPath(arr, json, basePath) {
      const type = this.validateType(json)
      if (type === 'object') {
        for (const key in json) {
          const item = {
            key,
            path: `${basePath}.${key}`
          }
          const childType = this.validateType(json[key])
          item.type = childType
          if (childType === 'object' || childType === 'array') {
            item.leaf = true
            item.children = []
            this.jsonPath(item.children, json[key], item.path)
          } else {
            item.leaf = false
            item.value = json[key]
          }
          arr.push(item)
        }
      } else if (type === 'array') {
        json = json[0]
        if (json === undefined) return
        for (const key in json) {
          const item = {
            key,
            path: `${basePath}[*].${key}`
          }
          const childType = this.validateType(json[key])
          item.type = childType
          if (childType === 'object' || childType === 'array') {
            item.leaf = true
            item.children = []
            this.jsonPath(item.children, json[key], item.path)
          } else {
            item.leaf = false
            item.value = json[key]
          }
          arr.push(item)
        }
      }
    },
    validateType(val) {
      // 校验JSON数据类型
      const type = typeof val
      if (type === 'object') {
        if (Array.isArray(val)) {
          return 'array'
        } else if (val === null) {
          return 'null'
        } else {
          return 'object'
        }
      } else {
        return type
      }
    }
  }

}
</script>

<style>

</style>
