js three ways to convert a string into a json object

js three ways to convert a string into a json object

Regardless of whether the string contains escape characters, it can be converted into a Json object

1, The eval function that comes with js needs to add parentheses eval('('+str+')');

function strToJson(str){
  var json = eval('(' + str + ')');
  return json;
}

2, new Function form

function strToJson(str){
  var json = (new Function("return " + str))();
  return json;
}

3, the global JSON object

function strToJson(str){
  return JSON.parse(str);
}

Using this method is slightly more restrictive, and the JSON specification must be strictly followed. For example, attributes must be enclosed in quotation marks, as follows

var str = '{name:"jack"}';
var obj = JSON.parse(str); // --> parse error

If the name is not enclosed in quotation marks, all browsers using JSON.parse will throw an exception, and the parsing will fail.

If the string is undefined or '', using the above three methods will report an error, so you need to make a special judgment whether the string is undefined or an empty string, if not, you can use the above three methods to convert, generally use the first method, the simplest.

Reposted from : Three ways js converts strings into json

javascript converts objects into json strings

JSON.stringify

The JSON.stringify method converts an object into a JSON string form

const userInfo= {
    name: 'zs',
    age: 20
}
console.log(JSON.stringify(userInfo));
// {"name":"zs","age":20}

JSON.stringify syntax

Syntax: There can be three parameters, the first is to pass in the value to be serialized, the second is a function or array, and the third is to add indentation, spaces and newlines to the text

JSON.stringify(value, replacer, space)

value:第一个参数,将要序列后成 JSON 字符串的值。
replacer:【可选】第二个参数
(1) 如果该参数是一个函数,则在序列化过程中,被序列化的值的每个属性都会经过该函数的转换和处理;
(2) 如果参数是一个数组,则仅转换该数组中具有键值的成员。成员的转换顺序与键在数组中的顺序一样。
(3) 如果该参数为未提供或者null ,则对象所有的属性都会被序列化。
space:【可选】第三个参数,美化文本格式,文本添加缩进、空格和换行符,
(1) 如果 该参数 是一个数字,则返回值文本在每个级别缩进指定数目的空格
(2) 该参数最大值为10,如果 该参数大于 10,则文本缩进 10 个空格。
(3)该参数也可以使用非数字,如:\t。最大值为10

最多使用方式

JSON.stringify(eval(stu, null, 2)

如果想把包含转义字符的字符串转成 json 字符串

先试用 eval 把字符串转成 json 对象,然后使用 JSON.stringify 把 json 对象转成 json 字符串

JSON.stringify(eval(`(${stu})`), null, 2)

如果还需要特别判断一下空字符串,加个三目运算符就行

stu ? JSON.stringify(eval(`(${stu})`), null, 2) : ''

参考:

js将字符串转换成json的三种方式

JSON.stringify用法

Guess you like

Origin blog.csdn.net/qq_41767116/article/details/128796357