Menu
Let’s say we have a complex object, and we’d like to convert it into a string, to send it over a network, or just to output it for logging purposes.
Naturally, such a string should include all important properties.
Javascript JSON: Objects. Earlier, JSON parsers did a bit more than what JavaScript eval functions could do, i.e parse, interpret and return the data as JavaScript objects and arrays. But now JSON object has two methods: stringify and parse stringify: To serialize JavaScript objects into a JSON string. No, the standard way to serialize to JSON is to use an existing JSON serialization library. If you don't wish to do this, then you're going to have to write your own serialization methods. Cross-browser JSON Serialization in JavaScript In this article we will examine the benefits of object serialization, the current browser implementations, and develop some code that could help your. Mar 30, 2017 How to: Serialize and deserialize JSON data JSON (JavaScript Object Notation) is an efficient data encoding format that enables fast exchanges of small amounts of data between client browsers and AJAX-enabled Web services. No, the standard way to serialize to JSON is to use an existing JSON serialization library. If you don't wish to do this, then you're going to have to write your own serialization methods. Serializing to JSON in jQuery. How to access values in JSON object?-3. Mar 03, 2019 The JSON.stringify method converts a JavaScript object or value to a JSON string, optionally replacing values if a replacer function is specified or optionally including only the specified properties if a replacer array is specified.
We could implement the conversion like this:
…But in the process of development, new properties are added, old properties are renamed and removed. Updating such
toString
every time can become a pain. We could try to loop over properties in it, but what if the object is complex and has nested objects in properties? We’d need to implement their conversion as well.Luckily, there’s no need to write the code to handle all this. The task has been solved already.
JSON.stringify
The JSON (JavaScript Object Notation) is a general format to represent values and objects. It is described as in RFC 4627 standard. Initially it was made for JavaScript, but many other languages have libraries to handle it as well. So it’s easy to use JSON for data exchange when the client uses JavaScript and the server is written on Ruby/PHP/Java/Whatever.
JavaScript provides methods:
JSON.stringify
to convert objects into JSON.JSON.parse
to convert JSON back into an object.
For instance, here we
JSON.stringify
a student:The method
JSON.stringify(student)
takes the object and converts it into a string.The resulting
json
string is called a JSON-encoded or serialized or stringified or marshalled object. We are ready to send it over the wire or put into a plain data store.Please note that a JSON-encoded object has several important differences from the object literal:
- Strings use double quotes. No single quotes or backticks in JSON. So
'John'
becomes'John'
. - Object property names are double-quoted also. That’s obligatory. So
age:30
becomes'age':30
.
JSON.stringify
can be applied to primitives as well.JSON supports following data types:
- Objects
{ ... }
- Arrays
[ ... ]
- Primitives:
- strings,
- numbers,
- boolean values
true/false
, null
.
For instance:
JSON is: meetup}. In other words, the first
(key, value)
pair has an empty key, and the value is the target object as a whole. That’s why the first line is ':[object Object]'
in the example above.Serialize Json Javascript Converter
The idea is to provide as much power for
replacer
as possible: it has a chance to analyze and replace/skip even the whole object if necessary.Formatting: space
The third argument of
JSON.stringify(value, replacer, space)
is the number of spaces to use for pretty formatting.Previously, all stringified objects had no indents and extra spaces. That’s fine if we want to send an object over a network. The
space
argument is used exclusively for a nice output.Here
space = 2
tells JavaScript to show nested objects on multiple lines, with indentation of 2 spaces inside an object:The
space
parameter is used solely for logging and nice-output purposes.Custom “toJSON”
Like
toString
for string conversion, an object may provide method toJSON
for to-JSON conversion. JSON.stringify
automatically calls it if available.For instance:
Here we can see that
date
(1)
became a string. That’s because all dates have a built-in toJSON
method which returns such kind of string.Now let’s add a custom
toJSON
for our object room
(2)
:As we can see,
toJSON
is used both for the direct call JSON.stringify(room)
and when room
is nested in another encoded object.![Deserialize Deserialize](https://www.bennadel.com/resources/uploads/2017/json-stringify-will-recursively-call-tojson.png)
JSON.parse
To decode a JSON-string, we need another method named JSON.parse.
The syntax:
- str
- JSON-string to parse.
- reviver
- Optional function(key,value) that will be called for each
(key, value)
pair and can transform the value.
For instance:
Or for nested objects:
The JSON may be as complex as necessary, objects and arrays can include other objects and arrays. But they must obey the same JSON format.
Here are typical mistakes in hand-written JSON (sometimes we have to write it for debugging purposes):
Besides, JSON does not support comments. Adding a comment to JSON makes it invalid.
There’s another format named JSON5, which allows unquoted keys, comments etc. But this is a standalone library, not in the specification of the language.
The regular JSON is that strict not because its developers are lazy, but to allow easy, reliable and very fast implementations of the parsing algorithm.
Using reviver
Imagine, we got a stringified
meetup
object from the server.It looks like this:
…And now we need to deserialize it, to turn back into JavaScript object.
Let’s do it by calling
JSON.parse
:Json Serialize Blob Javascript
Whoops! An error!
The value of
meetup.date
is a string, not a Date
object. How could JSON.parse
know that it should transform that string into a Date
?Let’s pass to
JSON.parse
the reviving function as the second argument, that returns all values “as is”, but date
will become a Date
:By the way, that works for nested objects as well:
Summary
- JSON is a data format that has its own independent standard and libraries for most programming languages.
- JSON supports plain objects, arrays, strings, numbers, booleans, and
null
. - JavaScript provides methods JSON.stringify to serialize into JSON and JSON.parse to read from JSON.
- Both methods support transformer functions for smart reading/writing.
- If an object has
toJSON
, then it is called byJSON.stringify
.
Serializing form data means to get all values of form fields in a text string (in URL query string format).
For example:
jQuery has a method “serialize()” to serialize form data. However, JavaScript serialize form do not support this method directly. To allow form data serialize in JavaScript, we must import a library from google.
Form data can be serialized by both jQuery and JavaScript but, the major difference between them is that, jQuery’sserialize() method returns form field values in top down sequence whereas, serialize JavaScript returns it in bottom up sequence.
Here in this example you will see that contact number field’s value will be shown up first in the query string which is the last field of the form.
Javascript serialize method:
jQuery serialize method:
In our example, we have created an HTML form with some common form fields like “text”, “checkbox” and “radio” and to get their values, we used JavaScript serialize method which returns a string.
Watch out the live demo or download the code to use it.
Download script
Complete HTML and JavaScript codes are given below.
HTML file: serialize.html
Given below our complete HTML form.
Given below our complete HTML form.
JavaScript file: serialize.js
In the below script, we validate all fields and then serialize form data.
CSS File: style.css
Styling HTML elements.
Conclusion:
So, this was all about form data serialization using JavaScript. Hope you like it, keep reading our other blogs post and do provide us your valuable feedback.
So, this was all about form data serialization using JavaScript. Hope you like it, keep reading our other blogs post and do provide us your valuable feedback.
Check out our latest blogs here –
- Chrome Extension Tutorial: to Display RSS Blog Feeds