In this article I will explain with an example, how to deserialize JSON string to JSON object using
JavaScript.
HTML Markup
The following HTML Markup consists of:
TextBox – For capturing value of Name, Age, City and Country.
Button – For parsing JSON string.
The Button has been assigned with a
JavaScript onclick event handler.
<table>
<tr>
<td>Name:</td>
<td><input type="text" id="txtName" /></td>
</tr>
<tr>
<td>Age:</td>
<td><input type="text" id="txtAge" /></td>
</tr>
<tr>
<td>City:</td>
<td><input type="text" id="txtCity" /></td>
</tr>
<tr>
<td>Country:</td>
<td><input type="text" id="txtCountry" /></td>
</tr>
</table>
<br />
<input type="button" id="btnParse" value="Parse JSON" onclick="ParseJSON()" />
Deserializing JSON string to JSON object using JavaScript
First, the JSON Array is crated with Person details.
Inside the
ParseJSON JavaScript function, using
eval function the JSON data is parsed.
Once the JSON string is parsed and converted to JSON object the values are set to their respective TextBoxes.
<script type="text/javascript">
var json = "{Name: 'Mudassar Khan', Age: 27, City: 'Mumbai', Country: 'India'}";
function ParseJSON() {
var person = eval('(' + json + ')');
document.getElementById("txtName").value = person.Name;
document.getElementById("txtAge").value = person.Age;
document.getElementById("txtCity").value = person.City;
document.getElementById("txtCountry").value = person.Country;
}
</script>
Screenshot
Browser Compatibility
* All browser logos displayed above are property of their respective owners.
Demo
Downloads