Click here to Skip to main content
Click here to Skip to main content
Technical Blog

Serialize JSON Object to String

, 16 Feb 2011 CPOL
Rate this:
Please Sign up or sign in to vote.
Serialize JSON Object to String

A simple way to serialize a JSON object is to iterate through the object’s property and create a JSON formatted string. All the properties and functions in a JSON object can be read just like an associative array or a name/value pair. This allows us to list all the keys and query the object for the values using the keys. Look at the following script:

var myJSON = {
    FirstName: '',
    LastName: '',
    Email: '',
    load: function () {
        //implementation here
    serialize: function () {
        var json = "";
        for (var key in this) {
            if (typeof this[key] != 'function') {
                json += (json != "" ? "," : "") + key + ":'" + this[key] + "'";
        json = '[{' + json + '}]';
        return json;

The serialize function uses a for loop to get all the keys in the object. It checks if the type is not a function because, for this case, we just want to extract the user data values and ignore the functions. You could also extract the contents of the function by just removing the if condition. To build the formatted string, the function concatenates a string with the key/value pair until it reads all the keys. The following sample script sets the property values and serializes the data to a string:

//client code to set properties and serialize data
if (typeof (myJSON) != 'undefined') {
    myJSON.FirstName = "myfirstname";
    myJSON.LastName = "mylastname";
    myJSON.Email = "myemail";
    var data = myJSON.serialize();

The data variable contains a string with this format:


I hope this helps.


This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)


About the Author

ozkar garcia
Architect OG-BITechnologies
United States United States
My Blog
Follow on   Twitter

Comments and Discussions

GeneralMy vote of 1 PinmemberRagnor22-Feb-11 11:34 
GeneralMy vote of 5 Pinmemberjustinonday16-Feb-11 20:41 
GeneralMy vote of 4 Pinmemberjustinonday16-Feb-11 20:41 
GeneralMy vote of 5 Pinmemberozkar garcia16-Feb-11 4:29 
GeneralProblems with quoted strings etc Pinmemberjsc4215-Feb-11 7:33 
GeneralRe: Problems with quoted strings etc Pinmemberozkar garcia15-Feb-11 10:19 

General General    News News    Suggestion Suggestion    Question Question    Bug Bug    Answer Answer    Joke Joke    Rant Rant    Admin Admin   

Use Ctrl+Left/Right to switch messages, Ctrl+Up/Down to switch threads, Ctrl+Shift+Left/Right to switch pages.

| Advertise | Privacy | Terms of Use | Mobile
Web01 | 2.8.150327.1 | Last Updated 16 Feb 2011
Article Copyright 2011 by ozkar garcia
Everything else Copyright © CodeProject, 1999-2015
Layout: fixed | fluid