Home > Web Front-end > JS Tutorial > How to convert string to object in nodejs

How to convert string to object in nodejs

青灯夜游
Release: 2021-12-31 13:43:10
Original
3278 people have browsed it

Nodejs method of converting strings into objects: 1. Use the eval() function, syntax "eval('(' str ')')"; 2. Use the "JSON.parse()" function, Syntax "JSON.parse(str)".

How to convert string to object in nodejs

The operating environment of this tutorial: windows7 system, nodejs version 12.19.0, DELL G3 computer.

Conversion between NodeJS objects and strings

String to object:

1, use eval function

var str='{"F001":true,"F002":false,"F003":false }';
var obj = eval('('+str+')'); //必须加括号才可以将该字符串转换成对象,加括号表示运行里面的代码。
console.log(obj.F001);//true
Copy after login

2, use JSON.parse function

var str='{"F001":true,"F002":false,"F003":false }'; //属性名必须已经被引号括起,否则转换将失败。
var obj=JSON.parse(str);
console.log(obj.F002); //false
Copy after login

Object to string:

var obj={F001:true,F002:false,F003:false };
console.log(JSON.stringify(obj));//Node原生支持JSON
//{"F001":true,"F002":false,"F003":false}
Copy after login

For more node-related knowledge, please visit: nodejs tutorial! !

The above is the detailed content of How to convert string to object in nodejs. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template