Filter and Convert JSON object to String

Let us see how to filter only certain members of the JSON object and convert it into JSON text. In the example shown below, I will be serializing only the 'Name' member

<html xmlns="http://www.w3.org/1999/xhtml" >
<head>
<title>JSON to String (By DevCurry.com)</title>
<script type="text/javascript">
var jsonObj = [
{ "ID": "1", "Name": "Keith" },
{ "ID": "2", "Name": "Bill" }
];

// Filter only "Name"
var filter = new Array();
filter[0] = "Name";

var jsonText = JSON.stringify(jsonObj, filter);
alert(jsonText);
</script>
</head>
<body>

As you can see, we are using JSON.stringify and using a filter to serialize only the “Name” member of the JSON object to JSON text.

OUTPUT

image

1 comment:

  1. Thanks a lot for this. It really helped me! Greetings from Argentina!

    ReplyDelete