parse json string

后端 未结 5 1152
轻奢々
轻奢々 2020-12-14 04:36

I have the following Json string

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


        
相关标签:
5条回答
  • 2020-12-14 05:18

    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);
    }
    
    0 讨论(0)
  • 2020-12-14 05:25
    <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>
    
    0 讨论(0)
  • 2020-12-14 05:31

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

    var jsonString = '{"key":"value","otherkey":"othervalue"}';
    data = $.parseJSON(jsonString);
    alert(data.key); // Shows: value
    
    0 讨论(0)
  • 2020-12-14 05:33

    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;
    
    0 讨论(0)
  • 2020-12-14 05:42
    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/

    0 讨论(0)
提交回复
热议问题