Users Online

· Guests Online: 136

· Members Online: 0

· Total Members: 188
· Newest Member: meenachowdary055

Forum Threads

Newest Threads
No Threads created
Hottest Threads
No Threads created

Latest Articles

Convert String to JSON

Convert String to JSON

Convert String to JSON

Introduction to Convert String to JSON

Let us see about the Conversion of String to JSON, we know JSON serialization and deserialization, JSON stringify, JSON parser, etc. Conversion of String to JSON can be done 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 input string to JSON object by following some specifications. Convert String to JSON converts an input string to a JSON object for the user to have output in a readable format like a map or an array. This conversion is possible by JSON.parse() in JavaScript. In Java, the GSON object is used for conversion, whereas in Python, json.loads() is 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.

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.

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 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.

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 convert string to JSON, the string gets parsed to a JSON object, which can be used anywhere in the code. Here, before parsing, it is a string, so data cannot be encoded. It gets converted to JS object on parsing, which makes it possible to access everywhere in the code.

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}"));

Output:

Convert String to Json 1

In Java, we need to use Gson Library, a parser called JsonParser, which parses JSON string. Also, user can create a Gson instance and use the fromJson method. Gson is an open-source library for the conversion of string to Json in Java. Gson is responsible for its good performance.

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 String to Json 2

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:

date 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:

parse

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. As Json.parse() method in JavaScript converts JSON to JSON object. JSON is commonly used for exchanging data on server and web applications.

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>

Output:

Convert String to Json 5

Convert String to Json 6

Conclusion

We have seen how the conversion of string to JSON is done in JavaScript, along with few examples illustrated above. Were able to gain theoretical knowledge in converting string to JSON in Java and Python languages. 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. Hence parsing the input string or converting string to JSON is useful in developing software applications.

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.05 seconds
10,814,524 unique visits