Home > Web Front-end > JS Tutorial > How to convert object to string using javascript

How to convert object to string using javascript

青灯夜游
Release: 2023-01-05 16:11:35
Original
5971 people have browsed it

In JavaScript, you can use the "JSON.stringify()" method to convert objects into strings, with the syntax "JSON.stringify(object)". The "JSON.stringify()" method is used to convert js values ​​(objects or arrays) into JSON strings and back.

How to convert object to string using javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

In javascript, you can use the "JSON.stringify()" method to convert an object into a string.

Instance: Convert object to string

// 对象
var jsonObj = {
   "CityId":"18",
    "CityName":"西安2"
};

// 对象转换为字符串
var newString = JSON.stringify(jsonObj);
console.log(typeof newString); // 输出:string
console.log(newString); // 输出:{"CityId":"18","CityName":"西安2"}
Copy after login

Output:

How to convert object to string using javascript

JSON.stringify( ) method is used to convert a JavaScript value to a JSON string and then returns a string containing the JSON text.

Syntax:

JSON.stringify(value[, replacer[, space]])
Copy after login

Parameters:

How to convert object to string using javascript

##Example:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
</head>
<body>

<p id="demo"></p>
<script>
var str = {"name":"PHP中文网", "site":"http://www.php.cn"}
str_pretty1 = JSON.stringify(str)
document.write( "只有一个参数情况:" );
document.write( "<br>" );
document.write("<pre class="brush:php;toolbar:false">" + str_pretty1 + "
Copy after login
" ); document.write( "
" ); str_pretty2 = JSON.stringify(str, null, 4) //使用四个空格缩进 document.write( "使用参数情况:" ); document.write( "
" ); document.write("
" + str_pretty2 + "
Copy after login
" ); // pre 用于格式化输出 Rendering:

How to convert object to string using javascript

[Recommended learning:

javascript advanced tutorial]

The above is the detailed content of How to convert object to string using javascript. 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