Updated March 31, 2023
Introduction to JavaScript Parse String
Let us look at Parsing, which means analyzing and converting a set of instructions into a format that the runtime environment can understand and run. Browsers analyze the text which is made up of a sequence of tokens to determine its structure, the parse which further builds a data structure based on the tokens. These tokens involve start and end tags, attribute name and values which builds up the document tree. This javascript parsing is done at compile time or whenever there is a call to a method.
Syntax:
var variable_name = '{"variable1":"value", "variable2":”value”, "variable3":"value",…….}'
var object_name = JSON.parse(variable_name);
How does JavaScript Parse String work?
Below is the explanation:
Code:
<body>
<h2>Create object from JSON String</h2>
<p id="demo"></p>
<script>
var student = '{"name": "Jessy", "age": 15, "city": "India"}'
var obj = JSON.parse(student);
document.getElementById("demo").innerHTML = obj.name +", " + obj.age + ", " + obj.city;
</script>
</body>
</html>
Output:
Explanation: Here, the student is a variable that contains the student data, when parsed using JSON, student data is given to variable obj through which we can display the data by calling with the variable obj.
Examples to Implement JavaScript Parse String
Using JSON.parse on JSON is derived from the array, the method returns javascript array instead of an object. Let us consider JSON array which consists of Car models, we shall pass content as an array to a JSON object. Json_demo_array.txt is the content file that consists of data of car models.
[ “Ford”, “BMW”, “Audi”, “Fiat” ]Example #1
On checking the status code of HttpRequest we parse the JSON and try to display one of the elements of the array. We use the GET method to get the data from json_demo_array.txt file where we have the content to be displayed.
Code:
<html>
<body>
<h2>Content as Array</h2>
<p id="demo"></p>
<script>
var xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange = function()
{
if(this.readyState == 4 &&this.status == 200)
{
var myArr = JSON.parse(this.responseText);
document.getElementById("demo").innerHTML = myArr[2];
}
};
xmlhttp.open("GET", "Json_demo_array.txt", true);
xmlhttp.send();
</script>
</body>
</html>
Output:
Explanation: There are some exceptions which are included when working with JSON parsing for dates. We need to write the date as a string and then later can convert into a date object.k
Example #2
Code:
<!DOCTYPE html>
<html>
<body>
<h2>Conversion of string into date object</h2>
<p id="demo"></p>
<script>
var text = '{"name" : "Karthick", "birth": "2020-01-12", "city": "Canada"}';
var obj = JSON.parse(text);
obj.birth = new Date(obj.birth);
document.getElementById("demo").innerHTML = obj.name + ", " + obj.birth;
</script>
Output:
Explanation: Here ‘var obj = new Date(obj.birth)’ refers to creating Date object and passing the JSON text to new object.
Example # 3
Parameter Json.parse() function called reviver, which checks each property before returning values. Let us now see how to use reviver function
Code:
<html>
<body>
<h2>Conversion of string into date object</h2>
<p id="demo"></p>
<script>
var text = '{"name": "Karthick", "birth": "2020-01-12", "city": "Canada"}';
var obj = JSON.parse(text, function(key, value) {
if(key == "birth") {
return new Date(value);
} else {
return value;
}
} );
document.getElementById("demo").innerHTML = obj.name + ", " + obj.birth;
</script>
</body>
</html>
Output:
Explanation: Here, along with text, we pass the birth value as (key, value) pair to JSON.
Example #4
We also cannot parse functions to JSON, we need to write it as a string and convert back to function.
Code:
<!DOCTYPE html>
<html>
<body>
<h2>Conversion of string into a function.</h2>
<p id= "demo"></p>
<script>
var text = '{"name": "Karthick", "age": "function() {return 45;}", "city": "Canada"};
var obj = JSON.parse(text);
obj.age = eval("(" + obj.age + ")");
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age();
</script>
</body>
</html>
Output:
Let us look at the structure of this parser. Parser consists of two parts: Tokenizer and parsers. Some parsers do not depend on Lexer which is known as scanners parsers. Both tokenizer/ lexer and parser work one after another i.e tokenizer scans the input and produces matching tokens whereas parser scans the tokens in return and produces parsing results.
String Primitives and String Objects
Javascript differs between string primitive, an immutable datatype and String object. Let us see how to initialize new string primitive,
const stringPrimitive = "How are you?";
Initializing using String object:
cosntstringObject = new String("How are you?");
- To determine the type of value of the operator, we use ‘typeof’. For eg., typeofstringPrimitive; returns the string as output. In the case of string object, typeofstringObject return object as output.
- Parsing in Programming: Parsing in java where methods take the input string a return other data type, to split a file or other input data can be stored or manipulated.
- An Integer can be parsed using parseInt() function, let us consider ‘756’ which is considered as a string of char values 7, 5, 6. Lexer converts this string into integer 756. Consider date format “yyyy-MM-dd”
SimpleDateFormat format = newSimpleDateFormat("yyyy-MM-dd");
Date date = format.parse("2020-06-02");
- Yyyy is the year, – is a literal, MM is the month, – another literal and dd is the day. Java parses the date string into a pre-defined of parts and recognizing the parts by which parse function outputs data objects to store and manipulate data string.
- Little structures like parsing a hexadecimal number or floating number are defined throughout the language but java limits to integer, date, and float. These parsing functions are used because user input is mostly in the form of strings, before converting into java date type, a user needs to parse it. An exception comes when a user works with normal text, in this case, we need to leave the text as it is and use string functions for manipulation.
Conclusion
In the software world, code has syntax and programming languages are defined by a formal grammar, taking a line of code, breaking it into data elements and data operators i.e. translating source code to executable code.
As javascript is flexible and fault-tolerant, and syntax parser works to understand what the user wants, the user can able to hoist a variable before a declaration. In a global environment, users can even use the variable without declaring. String concatenation is also possible with integers and also can compare objects with primitives, call functions and pass no parameters. There is also something parser can handle is insertion of semicolon automatically. When a function gets called, semicolon; is inserted after return statement and undefined is returned as a result.
Recommended Articles
This is a guide to JavaScript Parse String. Here we discuss the introduction, how does it works and examples to implement with proper codes and outputs. You can also go through our other related articles to learn more –