Users Online

· Guests Online: 162

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

Convert Text to JSON

Convert Text to JSON

Convert Text to JSON

Introduction to Convert Text to JSON

Convert Text to JSON is nothing but converting normal text to JSON. JSON is a data-interchange format which is readable and helps in transmitting data between web applications and servers. For this conversion, we will be using a JSON method called ‘parse()’. This parser will be used to convert Text to JSON in JavaScript. JSON parser parses the text which returns a Javascript object. Parsing JSON is converting the JSON text to a JSON object by following some mentioned specifications. So based on the JSON object content, the result can be either a string, map or an array, etc.

Syntax:

JSON.parse(string, function)

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

Reviver function is an optional parameter which is used to transform result. 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.

For Example:

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

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

JSON syntax is subset of JS syntax.

How does Conversion of String/Text to JSON is done?

Javascript object, a data type in JS with properties and value pairs defined, JSON is data interchange formatter. Bunch of characters being formatted in various programs for easy communication, which returns JSON object corresponding to JSON text/string.

For Example:

Code:

var jsonSample = '{"employeeName": "Amar"}';
var obj = JSON.parse(jsonStr);
console.log(obj.employeeName); // prints "Amar"
console.log(jsonSample.employeeName); // prints undefined

When we parse JSON, the string gets converted to a JSON object which can be used anywhere in the code. Here, before parsing, it is a string, so data cannot be encoded. On parsing, it gets converted to JS object, which makes it possible to access everywhere in the code.

Examples of Convert Text to JSON

Given below are the examples of Convert Text 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}"));

Output:

Convert Text to JSON 1

Convert Text to JSON 2

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>

Output:

Convert Text to JSON 3

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>

Output:

data object

So here, the Date function in Javascript retrieves the date of birth in IST Indian Standard Time. Date objects are not allowed in JSON; hence we write it as a string and then convert or parse it to an object.

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>

Output:

Convert Text to JSON 5

As functions are not allowed in JSON, hence we include the function as a string and then parse it to a function. Functions lose their scope; eval () can be used to convert back to functions.

Example #5

Code:

<!DOCTYPE html>
<html>
<body>
<h2>Conversion of string to Date object using Reviver</h2>
<p id="demo"></p>
<script>
var sampleText = '{"employeeName":"Amar", "dob":"1986-06-12", "city":"Paris"}';
var obj = JSON.parse(sampleText, function (key, value) {
if (key == "dob") {
return new Date(value);
} else {
return value;
}
});
document.getElementById("demo").innerHTML = obj.employeeName + " was born on " + obj.dob + " and lives in " + obj.city;
</script>
</body>
</html> Output:

using reviver

Example #6

Code:

<!DOCTYPE html>
<html>
<body>
<h2>Using XMLHttpRequest to retrieve contents in a file</h2>
<p>The content is in JSON format, and can easily be converted to a JavaScript object</p>
<p id="demo"></p>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
var myObj = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myObj.name;
}
};
xmlhttp.open("GET", "json_demo.txt", true);
xmlhttp.send();
</script>
<p>Open <a href="json_demo.txt" target="_blank">json_demo.txt</a></p>
</body>
</html>

Output:

using XMLHttpRequest to retrieve contents

Convert Text to JSON 8

On clicking josn_demo.txt, the above array is displayed. On using JSON.parse on an array, the parser returns a javascript array instead of an object.

As we have illustrated all types of examples for Convert text to JSON, parsing a Date string to object, function, array, undefined values. While receiving data from a server, data is in the form of a string, and sometimes this string may contain multiple fields embedded. To use each field, we will not be able to use it in string format, and hence input string is parsed so that it becomes easy to use embedded fields in the string. We have seen what JSON.parser means and how it works. The concept of JSON.parser is to read and interpret input data to an object. Hence converting data would be useful to find out any embedded data inside the input string.

Comments

No Comments have been Posted.

Post Comment

Please Login to Post a Comment.

Ratings

Rating is available to Members only.

Please login or register to vote.

No Ratings have been Posted.
Render time: 1.51 seconds
10,807,124 unique visits