0

Hi how to Parse JSON string using JQuery or Javascript??

I have the JSON string like below format.

var JSON = "{ "UserID":"1","ClientID":"1","UserName":"User1"}"

I wanna to parse this JSON string. so that i can get

var UserID = 1
var ClientID = 1
UserName = User1

Can anybody help me out..

Thanks.

Felix Kling
  • 795,719
  • 175
  • 1,089
  • 1,143
watraplion
  • 287
  • 4
  • 17
  • possible duplicate of [How to parse JSON in JavaScript](http://stackoverflow.com/questions/4935632/how-to-parse-json-in-javascript) – Felix Kling Jul 09 '12 at 09:06
  • [Parse the JSON](http://stackoverflow.com/questions/4935632/how-to-parse-json-in-javascript) into a JavaScript object and extract the desired data. Read [Working with Objects](https://developer.mozilla.org/en/JavaScript/Guide/Working_with_Objects) if you don't know how to access properties of objects (JavaScript basics). – Felix Kling Jul 09 '12 at 09:07
  • I tried var obj = jQuery.parseJSON(JSON); It showing Object expected. But i tried with double quotes. – watraplion Jul 09 '12 at 09:13
  • this is working obj = JSON.parse(json); Thank you Felix and you all. – watraplion Jul 09 '12 at 09:22

2 Answers2

3

First of all, if you execute the JSON variable you have there, should give you a syntax error because you need to escape the double quotes, such as:

var JSON = "{ \"UserID\":\"1\",\"ClientID\":\"1\",\"UserName\":\"User1\"}";

or simply use single quotes to create the string

var JSON = '{ "UserID":"1","ClientID":"1","UserName":"User1"}';

Then you can just parse it using jQuery.parseJSON()

var obj = jQuery.parseJSON(JSON);
obj.UserID == 1; // true
Luca Matteis
  • 29,161
  • 19
  • 114
  • 169
2

Be wary of unescaped quotation marks in that string. I changed the outer quotes to single quotes.

var obj = jQuery.parseJSON('{ "UserID":"1","ClientID":"1","UserName":"User1"}')

var UserID = obj.UserID 
var ClientID = obj.ClientID
var UserName = obj.UserName
tb11
  • 3,056
  • 21
  • 29