Skip to content
Fix Code Error

Serializing to JSON in jQuery

March 13, 2021 by Code Error
Posted By: Herb Caudill

I need to serialize an object to JSON. I’m using jQuery. Is there a “standard” way to do this?

My specific situation: I have an array defined as shown below:

var countries = new Array();
countries[0] = 'ga';
countries[1] = 'cd';
...

and I need to turn this into a string to pass to $.ajax() like this:

$.ajax({
    type: "POST",
    url: "Concessions.aspx/GetConcessions",
    data: "{'countries':['ga','cd']}",
...

Solution

JSON-js – JSON in JavaScript.

To convert an object to a string, use JSON.stringify:

var json_text = JSON.stringify(your_object, null, 2);

To convert a JSON string to object, use JSON.parse:

var your_object = JSON.parse(json_text);

It was recently recommended by John Resig:

…PLEASE start migrating
your JSON-using applications over to
Crockford’s json2.js. It is fully
compatible with the ECMAScript 5
specification and gracefully degrades
if a native (faster!) implementation
exists.

In fact, I just landed a change in jQuery yesterday that utilizes the
JSON.parse method if it exists, now
that it has been completely specified.

I tend to trust what he says on JavaScript matters 🙂

All modern browsers (and many older ones which aren’t ancient) support the JSON object natively. The current version of Crockford’s JSON library will only define JSON.stringify and JSON.parse if they’re not already defined, leaving any browser native implementation intact.

Answered By: user18015

Related Articles

  • Is CSS Turing complete?
  • error LNK2005: ✘✘✘ already defined in…
  • List of Timezone IDs for use with FindTimeZoneById() in C#?
  • Reference - What does this regex mean?
  • How to call an Ember data function directly?
  • Does moment.js allow me to derive a timezone…
  • How do I include certain conditions in SQL Count
  • Downloading jQuery UI CSS from Google's CDN
  • How to use Servlets and Ajax?
  • How to show title in hover - css / jquery
  • CSS Float: Floating an image to the left of the text
  • Counting number of occurrences in an array in React Project
  • What's the best way to get the last element of an…
  • What is a NullReferenceException, and how do I fix it?
  • Creating a custom counter in Spark based on…
  • What does this symbol mean in JavaScript?
  • Combining Ember Table with Ember Data
  • React button to show an element
  • Vue 2 - update value of the array element after click event
  • Caching a jquery ajax response in javascript/browser
  • Convert array to nested JSON object - Angular Material tree
  • How to use GetX Navigation from a Page to itself
  • How to return a promise composed of nested models in…
  • vee-validate: Required only if a condition is met
  • VueJS select depending of another select
  • Using one iron-ajax element for multiple requests
  • Ember Data. Save model with "belongsTo" relationship
  • One to many relationship in two JSON arrays, lookup…
  • How to use html template with vue.js
  • npm install error in vue
  • How to use grpc-web in vue?
  • Smart way to truncate long strings
  • How do I return the response from an asynchronous call?
  • Best way to serialize/unserialize objects in JavaScript?
  • For-each over an array in JavaScript
  • How to parse an RSS feed using JavaScript?
  • Generating a drop down list of timezones with PHP
  • Parse JSON in C#
  • How to auto insert the current user into my db when…
  • Merge list of results into a single variable with Python
  • LNK2019 símbolo externo public: bool __thiscall ……
  • Laravel + Vue + Axios issue with POST method
  • Require.js load timeout for…
  • Active tab issue on page load HTML
  • Where do I find the current C or C++ standard documents?
  • Using StringWriter for XML Serialization
  • Latest jQuery version on Google's CDN
  • Sort table rows In Bootstrap
  • How does PHP 'foreach' actually work?
  • How to use php serialize() and unserialize()
  • Svelte application bug: changing the contents of an…
  • Serialize and Deserialize Json and Json Array in Unity
  • Using IS NULL or IS NOT NULL on join conditions -…
  • Improve INSERT-per-second performance of SQLite
  • How to use java.net.URLConnection to fire and handle…
  • Django 2.2 cannot serialize default values once…
  • How to serialize class to JSON, where property is of…
  • How do I use the nohup command without getting nohup.out?
  • Cast/initialize submodels of a Backbone Model
  • Access Data In Next.js From PostgreSQL Database?
  • How to access elements of a JArray (or iterate over them)
  • require.js loaded modules are null for bootstrap and parse
  • How to convert JSON to CSV format and store in a variable
  • How would I be able to multiple select and pass data…
  • PHP parse/syntax errors; and how to solve them
  • In this tic tac toe game, why the last move of last…
  • How can I filter through an array an return it…
  • XML Serialize generic list of serializable objects
  • Filterable gallery using slick.js
  • jQuery Mobile: document ready vs. page events
  • Aurelia route matching
  • Upvote and Downvote with Backbone, Express and Mongoose
  • How to force a POST request when saving a model?
  • Jquery/Ajax Form Submission…
  • Parse.View.extend - "cannot read property 'extend'…
  • Is it possible to apply CSS to half of a character?
  • binary search tree is not working properly, but the…
  • How can I get the correct ID assigned to the delete function
  • Assignen a template function with Variadic arguments…
  • eXist-db send JSON via POST request using eXPath Http_module
  • Style jQuery autocomplete in a Bootstrap input field
  • TypeScript metadata reflection references other…
  • How can I access and process nested objects, arrays or JSON?
  • Playing HTML5 video on fullscreen in android webview
  • Representing null in JSON
  • Getting Dropwizard Client And Jersey/HTTP I/O Error…
  • How to parse deserialized object back into arrays?
  • Serialize the response from backend to store ember store
  • How to bind change event in Backbone?
  • How can I re-render a view after deleting an object…
  • What is a "cache-friendly" code?
  • What is null in Java?
  • Are the days of passing const std::string & as a…
  • How to convert number to words in java
  • How to write the following test in Jasmine
  • The null object does not have a method []=
  • NextJs: Static export with dynamic routes
  • Uploading both data and files in one form using Ajax?
  • commandButton/commandLink/ajax action/listener…
  • Where and why do I have to put the "template" and…

Disclaimer: This content is shared under creative common license cc-by-sa 3.0. It is generated from StackExchange Website Network.

Post navigation

Previous Post:

AngularJS ngClass conditional

Next Post:

Send JSON data via POST (ajax) and receive json response from Controller (MVC)

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

.net ajax android angular arrays aurelia backbone.js bash c++ css dataframe ember-data ember.js excel git html ios java javascript jquery json laravel linux list mysql next.js node.js pandas php polymer polymer-1.0 python python-3.x r reactjs regex sql sql-server string svelte typescript vue-component vue.js vuejs2 vuetify.js

  • you shouldn’t need to use z-index
  • No column in target database, but getting “The schema update is terminating because data loss might occur”
  • Angular – expected call-signature: ‘changePassword’ to have a typedeftslint(typedef)
  • trying to implement NativeAdFactory imports deprecated method by default in flutter java project
  • What should I use to get an attribute out of my foreign table in Laravel?
© 2022 Fix Code Error