Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert a JSON string to an object?

How can I convert a JSON string to an object in JavaScript? Is there a method that does this?

Something like:

var x = "{  id: 5, name: 'hello'  }";
var y = /*something*/(x);

alert(y.id + " " + y.name);
like image 861
BrunoLM Avatar asked Jun 10 '10 11:06

BrunoLM


People also ask

How do I convert a JSON file to an object?

Convert JSON String to JavaScript Object The JSON module offers two methods - stringify() , which turns a JavaScript object into a JSON String, and parse() , which parses a JSON string and returns a JavaScript object.

How do you convert a string to a JSON object in Python?

Use the json.loads() function. The json. loads() function accepts as input a valid string and converts it to a Python dictionary. This process is called deserialization – the act of converting a string to an object.

Which method is used to convert JSON data to object?

JSON parsing is the process of converting a JSON object in text format to a Javascript object that can be used inside a program. In Javascript, the standard way to do this is by using the method JSON. parse() , as the Javascript standard specifies.

Which method converts a JSON string to a JavaScript object?

The JSON.parse() method parses a JSON string, constructing the JavaScript value or object described by the string.


2 Answers

As per the comments and question history it look like that you're already using jQuery. In that case, it's good to know that jQuery ships with a new parseJSON() function since version 1.4.1 which was released late January this year. Consider upgrading if you're not at 1.4.1 yet. Here's an extract of relevance from its API documentation:

Description: Takes a well-formed JSON string and returns the resulting JavaScript object.

jQuery.parseJSON( json ) version added: 1.4.1

json The JSON string to parse.

Passing in a malformed JSON string will result in an exception being thrown. For example, the following are all malformed JSON strings:

  • {test: 1} (test does not have double quotes around it).
  • {'test': 1} ('test' is using single quotes instead of double quotes).

Additionally if you pass in nothing, an empty string, null, or undefined, 'null' will be returned from parseJSON. Where the browser provides a native implementation of JSON.parse, jQuery uses it to parse the string. For details on the JSON format, see http://json.org/.

Example:

Parse a JSON string.

var obj = jQuery.parseJSON('{"name":"John"}');
alert( obj.name === "John" );
like image 185
BalusC Avatar answered Oct 03 '22 16:10

BalusC


Use json2 lib : http://www.json.org/js.html

like image 22
Aif Avatar answered Oct 03 '22 15:10

Aif