6

I have the following Json string

{ "Users" : [ 
    { "Name" : "user99",
      "Value" : "test"
    },
    { "Name" : "test2",
      "Value" : "test"
    }
 ] 
}

I am trying to parse it and print out each name and value - what is the easiest way to do this ? I tried jQuery.parseJSON but I do not know how to use it I guess

Sample code would be great

5
  • 2
    From where are you obtaining this string? Commented Feb 21, 2011 at 20:51
  • What happens if you use jQuery.parseJSON? Have you had a look at the example? There is not much what you can do with that function ;) Commented Feb 21, 2011 at 20:54
  • my application queries a database and builds the json string for processing Commented Feb 21, 2011 at 20:54
  • How are you obtaining this string? Commented Feb 21, 2011 at 20:55
  • Just so you know, a more compact format for the same data is the following: {"Users": {"user99" : "test2", "test2" : "test"}...]. This format keys the users by their "Name". Commented Aug 29, 2011 at 21:05

5 Answers 5

12
var json = '{"Users":[{"Name":"user999","Value":"test"},{"Name":"test2","Value":"test"}]}';

var json_parsed = $.parseJSON(json);

for (var u = 0; u < json_parsed.Users.length; u++){
    var user = json_parsed.Users[u];
    $('body').append($('<p>').html('User: '+user.Name+'<br />Value: '+user.Value));
}

Results in:

<p>User: user999<br />Value: test</p>
<p>User: test2<br />Value: test</p>

jsFiddle Example: http://jsfiddle.net/bradchristie/XtzjZ/1/

Sign up to request clarification or add additional context in comments.

Comments

2

You actually have an array of objects so..

var obj = $.parseJSON(string);

var users = obj.users;    

for x in users {
    alert(users[x].Name);
    alert(users[x].Value);
}

Comments

2

You can use jQuery.parseJSON, here's an example:

var jsonString = '{"key":"value","otherkey":"othervalue"}';
data = $.parseJSON(jsonString);
alert(data.key); // Shows: value

Comments

2
<script>
var str = '{"Users":[{"Name":"user999","Value":"test"},{"Name":"test2","Value":"test"}]}';
str = eval('('+str+')');
alert(str.Users[0].Name);

//var str = '{"x":{"a":"1"}}';
//alert(str.x.a);
</script>

Comments

0

For the JSON you have given, $.parseJSON should return an object, myObj, that can be accessed like so:

var users = myObj.Users,
    user0_name = users[0].Name;

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.