How to convert String to JSON - JavaScript

How to convert String to JSON - JavaScript
Techiio-author
Written by Sagar RabidasMarch 11, 2022
7 min read
JavaScript
7 VIEWS 2 LIKES 0 DISLIKES SHARE
2 LIKES 0 DISLIKES 7 VIEWS SHARE
Techiio-author
Sagar Rabidas

Software Developer

In this blog, we will discuss Convert String to JSON

Introduction to Convert String to JSON:-

We know JSON serialization and deserialization, JSON stringify, JSON parser, and so on. Conversion of string to JSON may be finished in javascript, java, python, and many other languages too. So, what do you mean by this conversion of string to JSON? JSON. Parse method is used to convert the entered string to JSON object by using following some specs. Convert string to JSON converts an enter string to a JSON item for the user to have output in a readable format like a map or an array. This conversion is feasible by JSON.Parse() in javascript. In java, the JSON object is used for conversion, whereas in python, JSON.Masses() are used for this conversion.

Syntax of Convert String to JSON:-

Given below is the syntax mentioned:

JavaScript:

var obj = JSON.parse(string, function);

Arguments ‘string’ is a required parameter where a string is written in JSON format.

The reviver function is an optional parameter that is used to transform results. If this reviver function returns a valid value, the item value gets replaced with a transformed value. If in case, the reviver returns undefined, then the item is deleted.

Example:

Code:
var obj = JSON.parse('{ "employeeName":"Amar", "age":36, "city":"Paris"}');

SyntaxError exception is thrown if the string to parse is not a valid JSON.

JSON syntax is a subset of JS syntax.

Java:

Gson g = new Gson();

Python:

jsonString = json.loads(input_string);

Conversion of String to JSON in JavaScript:-

JSON item, a data type in js with properties and cost pairs defined, JSON is information interchange format. A bunch of characters is formatted in various programs for easy conversation, which returns JSON items corresponding to JSON textual content/ string.

Example:

Code:
var jsonSample = ‘{“employeeName”: “Amar”}’;
var obj = JSON.parse(jsonStr);
console.log(obj.employeeName); // prints “Amar”
console.log(jsonSample.employeeName); // prints undefined

Examples of Convert String to JSON:-

Given below are the examples of Convert String to JSON:

Example #1

Code:
const jsonSample = '{"result":false, "count":24}';
const obj = JSON.parse(jsonSample);
console.log(obj.count);
console.log(obj.result);
console.log(JSON.parse('{}'));
console.log(JSON.parse('true'));
console.log(JSON.parse('"amar"'));
console.log(JSON.parse('[14, 45, "true"]'));
console.log(JSON.parse('null'));
//console.log(JSON.parse('[11, 22, 33, 44, ]'));
//console.log(JSON.parse('{"dob" : 34, }'));
//console.log(JSON.parse("{'age': 10}"));

Example #2

Code:
<!DOCTYPE html>
<html>
<body>
<h2>Parsing from JSON String</h2>
<p id="demo"></p>
<script>
var txt = '{"employeeName":"Amar", "age":36, "city":"Paris"}'
var obj = JSON.parse(txt);
document.getElementById("demo").innerHTML = obj.employeeName + " of age " + obj.age + " lives in " + obj.city;
</script>
</body>
</html>

Example #3

Code:
<!DOCTYPE html>
<html>
<body>
<h2>Conversion of JSON string to date object</h2>
<p id="demo"></p>
<script>
var sampleText = '{"employeeName":"Amar", "dob":"1986-06-24", "city":"Paris"}';
var obj = JSON.parse(sampleText);
obj.dob = new Date(obj.dob);
document.getElementById("demo").innerHTML = obj.employeeName + " was born on " + obj.dob + " in " + obj.city;
</script>
</body>
</html>

Example #4

Code:
<!DOCTYPE html>
<html>
<body>
<h2>Conversion of JSON string to function using parse</h2>
<p id="demo"></p>
<script>
var sampleText = '{"employeeName":"Amar", "age":"function() {return 34;}", "city":"Paris"}';
var obj = JSON.parse(sampleText);
obj.age = eval("(" + obj.age + ")");
document.getElementById("demo").innerHTML = obj.employeeName + " of age " + obj.age() + " lives in " + obj.city;
</script>
</body>
</html>

Example #5

Code:
<!DOCTYPE html>
<html>
<head>
<title>Conversion of String to JSON in JavaScript</title>
</head>
<body>
<pre id="jsonData"
style="border:solid 1px #CCC;padding:0 6px;">
[
{
"employeeID": "101",
"employeeName": "Saideep",
"employeeType": "SSE",
"employer": "Infy"
},
{
"employeeID": "102",
"employeeName": "Karthick",
"employeeType": "SE",
"employer": "CG"
},
{
"employeeID": "103",
"employeeName": "Meghana",
"employeeType": "TL",
"employer": "PWC"
}
] </pre>
<p>
<input type="button" id="btnClick" value="Conversion of String to JSON" onclick="strngJson()" />
</p>
<p>Note: See the output in your browsers console window!</p>
</body>
<script>
function strngJson() {
var str = document.getElementById('jsonData').innerHTML;
var jsonObj = JSON.parse(str);
console.log(jsonObj);
}
</script>
</html>

Conclusion:-

We have visible how the conversion of string to JSON is done in javascript, together with a few examples illustrated above. Were able to gain theoretical information in changing the string to JSON in java and python languages. At the same time as receiving facts from a server, facts are in the form of a string, and on occasion, this string might also incorporate multiple fields embedded. To apply each area, we cannot be capable of using it in string layout, and consequently, the input string is parsed so that it will become clean to apply embedded fields inside the string. As a result, parsing the entered string or converting string to JSON is useful in growing software program applications.

Java
JavaScript
JSON
JS
HTML CSS
7 VIEWS 2 LIKES 0 DISLIKES SHARE
2 LIKES 0 DISLIKES 7 VIEWS SHARE
Was this blog helpful?
techiio-price-plantechiio-price-plantechiio-price-plantechiio-price-plantechiio-price-plan
You must be Logged in to comment
Code Block
Techiio-logo

Techiio is on the journey to build an ocean of technical knowledge, scouring the emerging stars in process and proffering them to the corporate world.

Follow us on:

Subscribe to get latest updates

You can unsubscribe anytime from getting updates from us
Developed and maintained by Wikiance
Developed and maintained by Wikiance