Handle field one by one during JSON to string conversion with JSON.stringify in JavaScript

Description

The following code shows how to handle field one by one during JSON to string conversion with JSON.stringify.

Example


<!-- ww  w  .  j  av  a  2 s.c om-->
<!DOCTYPE html>
<html>
<head>
<script type="text/javascript">
var book = {
"title": "JavaScript",
"authors": ["java2s.com"],
edition: 3,
year: 2011
};

var jsonText = JSON.stringify(book, function(key, value){
switch(key){
case "authors":
return value.join(",")
case "year":
return 2012;
case "edition":
return undefined;
default:
return value;
}
});
document.writeln(jsonText);
</script>

</head>
<body>

</body>
</html>

Click to view the demo

The code above generates the following result.

Handle field one by one during JSON to string conversion with JSON.stringify in JavaScript
Home »
  Javascript Tutorial »
    Data Type »
      JSON
Javascript Tutorial JSON
Add toJSON() method to object and have it r...
Control the string indention converting JSO...
Convert JSON object to String in JavaScript
Convert selected fields from JSON to String...
Convert string to date when converting stri...
Handle field one by one during JSON to stri...
Set indentation character during JSON seria...
Use JSON.parse() to create JSON object from...