[js] Recursive parsing of json strings

1. First of all, it is necessary to judge whether the value is a json string type

const isJSON = (str) => {
    
    
    if (typeof str === 'string') {
    
    
        try {
    
    
            let obj = JSON.parse(str);
            if(typeof obj === 'object' && obj ){
    
    
                return true;
            }else{
    
    
                return false;
            }
        } catch() {
    
    
            return false;
        }
    }else {
    
    
        return false
    }
}

2, and then use a recursive, loop judgment.

  • If the value is json, transfer it directly;
  • If not, determine whether he is an array or an object.
    1- If it is an array, it is necessary to loop the array. Only basic data types and objects can be placed in the array. 1.1-
    If the basic data types are placed, generally speaking, no parsing is required at all, but there is one situation: the typeof used for json strings is also string type, so we need to parse the json string. After the json string is parsed, there may be json strings in the child, so we need to recurse the whole process 1.2- If the object is
    placed, then loop the object and pass the key Get each attribute value of this object, and make judgments on the attribute value
    1.2.1- If the attribute value is a json string, it must be parsed. After parsing, the child of the json string may still have a json string, so just To recurse this attribute value
    1.2.2- If the attribute value is not a json string, then no operation is required
    2- It is an object, loop through each value of the object, and judge whether the value is a json string again, it must be parsed, After parsing, it is necessary to judge whether the child of the parsed data still has a json string...so just recurse directly
const demo = ((val: any) => {
    
    
  let data
  if(isJSON(val)) {
    
    
    data = JSON.parse(val)
    demo(data)
  }else {
    
    
    if(typeof val === 'object') {
    
    
      if(Array.isArray(val)) {
    
    
        val = val.map((item: any) => {
    
    
          if(typeof item === 'object' && !Array.isArray(item)) {
    
    
            Object.keys(item).forEach(key => {
    
    
              if(isJSON(item[key])) {
    
    
                item[key] = JSON.parse(item[key])
                Object.assign(item, {
    
     [key]: item[key] })
                demo(item[key])
              }              
            })
          }else {
    
    
            demo(item)
          }
          return item
        })
      }else {
    
    
        Object.keys(val).forEach(key => {
    
    
          demo(val[key])
        })
      }
    }else {
    
    
      return false
    }
  }
  return data
})
let a = demo(str)
console.log(a)

Guess you like

Origin blog.csdn.net/bbt953/article/details/130373659