Convert String To JSON Using JavaScript
Submitted by razormist on Sunday, May 24, 2020 - 21:36.
The code we will tackle about is Convert String To JSON using JavaScript. The program will convert any string that you enter in to a readable JSON object. The trick within this code is that you need to push all the string into an array object, then use JSON.stringtify() in order to safely display the JSON object as a string. To learn more about this, just follow the steps below.
There you have it we successfully created a Convert String To JSON using JavaScript. I hope that this simple tutorial help you to what you are looking for. For more updates and tutorials just kindly visit this site. Enjoy Coding!
Getting started:
First you have to download bootstrap framework, this is the link for the bootstrap that I used for the layout design https://getbootstrap.com/.The Main Interface
This code contains the interface of the application. To create this just write these block of code inside the text editor and save this as index.html.- <!DOCTYPE html>
- <html lang="en">
- <head>
- <meta charset="UTF-8" name="viewport" content="width=device-width, initial-scale=1"/>
- <link rel="stylesheet" type="text/css" href="css/bootstrap.css"/>
- </head>
- <body>
- <nav class="navbar navbar-default">
- <div class="container-fluid">
- </div>
- </nav>
- <div class="col-md-6 well">
- <hr style="border-top:1px dotted #ccc;"/>
- <div class="col-md-8">
- </div>
- <div class="col-md-4">
- <div class="form-group">
- <input type="text" class="form-control" id="firstname"/>
- </div>
- <div class="form-group">
- <input type="text" class="form-control" id="lastname"/>
- </div>
- <div class="form-group">
- <input type="text" class="form-control" id="address"/>
- </div>
- </div>
- </div>
- </body>
- </html>
Creating the Script
This code contains the script of the application. The code will forcefully convert the string into a JSON object. To do this just copy and write these block of codes inside the text editor, then save it as script.js inside the js folder.- var member = JSON.parse('{"member":[]}');
- function displayResult(firstname, lastname, address, json){
- document.getElementById('result').innerHTML = "<pre>"+json+"</pre>";
- firstname.value = "";
- lastname.value = "";
- address.value = "";
- }
- function convertString(){
- var firstname = document.getElementById('firstname');
- var lastname = document.getElementById('lastname');
- var address = document.getElementById('address');
- if(firstname.value == "" || lastname.value == "" || address.value == ""){
- alert("Please complete the required field!");
- }else{
- var str = '{"firstname": "'+firstname.value+'", "lastname": "'+lastname.value+'", "address": "'+address.value+'"}';
- member['member'].push(str);
- var stringify = JSON.stringify(member, null, ' ');
- var json = stringify.replace(/\\/g, '');
- displayResult(firstname, lastname, address, json);
- }
- }
Add new comment
- 176 views