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

How to convert object to string using javascript

青灯夜游
青灯夜游Original
2021-04-26 16:31:045956browse

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"}

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]])

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 + "
" ); document.write( "
" ); str_pretty2 = JSON.stringify(str, null, 4) //使用四个空格缩进 document.write( "使用参数情况:" ); document.write( "
" ); document.write("

" + str_pretty2 + "
" ); // pre 用于格式化输出

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!

Statement:
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