Example of Javascript Parse String
Using the JSON.parse() method in the Javascript parse string, you can change a string back into a JavaScript object as follows:
Example 1: In this example, we will return the country's name using JSON.parse.
var object_name = {'country':'Argentina'};
var string_name = JSON.stringify(obj_name);
var object2_name = JSON.parse(string_name)
console.log(obj2_name.country);
Output
Argentina
Example 2: Let us suppose that we have content files demo.txt that consists of IT Companies.
[ “TCS”, “Infosys”, “Wipro”, “Mahindra” ]
We will use JSON.parse to return the javascript array.
<html>
<body>
<h2>Company</h2>
<p id="practice"></p>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if(this.readyState == 4 &&this.status == 200)
{
var myArr = JSON.parse(this.responseText);
document.getElementById("practice").innerHTML = myArr[2];
}
};
xmlhttp.open("GET", "Json_demo_array.txt", true);
xmlhttp.send();
</script>
</body>
</html>
Output
Company
Wipro
Example 3: This example shows the conversion of a string into a date object.
<!DOCTYPE html>
<html>
<body>
<h2>String to Data Object Conversion</h2>
<p id="practice"></p>
<script>
var text = '{"name" : "John", "birth": "2000-12-31", "city": “England"}';
var obj = JSON.parse(text);
obj.birth = new Date(obj.birth);
document.getElementById("demo").innerHTML = obj.name + ", " + obj.birth;
</script>
Output
String to Data Object Conversion
John, Sun Jan 31 2000 05:30:00 GMT+0530 (India Standard Time)
Example 4: In this example, we will see the conversion of a string into a function.
<!DOCTYPE html>
<html>
<body>
<h2>String to Function Conversion.</h2>
<p id= "practice"></p>
<script>
var text = '{"name": "John", "age": "function() {return 40;}", "city": "Berlin"};
var obj = JSON.parse(text);
obj.age = eval("(" + obj.age + ")");
document.getElementById("practice").innerHTML = obj.name + ", " + obj.age();
</script>
</body>
</html>
Output
String to Function Conversion.
John,40
Reviver function in JSON.parse
The JSON.parse accepts an optional second parameter called a reviver function.
This function's goal is to alter the outcome before returning. This reviver function can be formulated as a simple filter function. Before being returned, all parsed values are passed through this reviver function in key-value pairs.
JSON.parse(jsonString, function (key, value)
{
// all key-value pairs in the JSON object are passed here
// return value for the key
return value;
});
Syntax Error in JSON.parse()
In our javascript parse string series now, we will cover the syntax error part. JSON,parse() will throw an syntax error in the below situation:-
🚀 JSON.parse() does not allow trailing commas.
// both will throw a SyntaxError
JSON.parse("[1, 2, 3, 4, ]");
JSON.parse('{"Cn" : 1, }');
🚀 JSON.parse() does not allow single quotes.
JSON.parse('{‘Cn’ : 1, }');
Conversion of Object to String in Javascript
JSON.stringify() is a function used to convert objects into strings in javascript. The example given below helps in understanding the conversion of an object back to a string using JSON.stringify().
var obj = {'fun':'coding'};
var str = JSON.stringify(obj);
console.log(typeof(str));
Output
string
Practice by yourself with the help of an online JS editor.
Frequently Asked Questions
What is Javascript?
Programmers use Javascript to build dynamic and interactive web applications and browsers worldwide. You can use it to add dynamic features to web pages that you can't do with just HTML and CSS.
What is DOM?
DOM stands for Document Object Model. This programming interface can add, change, or remove a website document's elements.
What is an Event Listener?
A JavaScript procedure that watches for events is known as an event listener. A user pressing a key on the keyboard or clicking the mouse is a basic example of an event.
Conclusion
Congratulations on finishing the blog! We have studied Javascript Parse String. We further looked at the reviver function and syntax error in Javascript Parse String.
We sincerely hope that this blog has improved your understanding of Javascript Parse String, and if you want to learn more, then you can check articles on:-
🤖 Introduction to Javascript
🦾 JS-HTML-DOM
🔑 Javascript vs. Jquery
Recommended problems -
Please refer to our guided pathways on Code studio to learn more about DSA, Competitive Programming, JavaScript, System Design, etc. Enroll in our courses, and use the accessible sample exams and questions as a guide. For placement preparations, look at the interview experiences and interview package.
Check out Wipro Interview Experience to learn about their hiring process.
Please do upvote our blogs if you find them helpful and informative!
Happy learning!