js judges whether a string is a json string

During our development, we may encounter that some of the values ​​returned by the backend are json strings and some are not, so we will report errors during rendering or logic operations!

 So we need to convert all json formats into ordinary strings.

Here I have encapsulated a method, you can copy it directly and use it:

1. Through modularization, this method is encapsulated separately, and can be referenced on the required page!

// 判断的是否是JSON字符串
export const type=(str)=>{
	if (typeof str == 'string') {
	      try {
	        var obj = JSON.parse(str);
			// 等于这个条件说明就是JSON字符串 会返回true
	        if (typeof obj == 'object' && obj) {
	          return true;
	        } else {
				//不是就返回false
	          return false;
	        }
	      } catch (e) {
	        return false;
	      }
	    }
	    return false;
}

2. Import through import {type} from "the file path where you store the method" !

3. Operate in the js logic to convert it to the format:

// 转换json格式
//如果是json格式 type(放入要检测的值) 会返回true 才会进入if里里面
if (type(val.value)) {
// console.log('json');
//确认是json格式后 我们进行转换 使用JSON.parse()
val.value = JSON.parse(val.value)
}

4. In the end, our value will become a string that can be used normally without additional operations!

It is best to suggest that you try to communicate with the backend to determine the returned format, so that you don't need to do it yourself.

The final operation is not easy, please upload the source for handling, thank you everyone!

Guess you like

Origin blog.csdn.net/m0_71231013/article/details/129042795