简体   繁体   English

Javascript如何用JSON数组解析JSON

[英]Javascript how to parse JSON with json array

I want to parse this using jQuery or javascript My JSON generated from the PHP code is as follows: 我想使用jQuery或javascript进行解析,我从PHP代码生成的JSON如下:

JSON JSON

{
         "user": {
             "name": "John Carter",
             "position": 0,
             "tickets": {
                 "months": [
                     "October",
                     "November"
                 ],
                 "start_Time": "2014-10-02",
                 "end_Time": "2014-11-21",
                 "Open": [
                     "1",
                     "3"
                 ]
             }
         }
}

My Javascript 我的Javascript

$.ajax({
                url: 'ajax.report.php',
                type: 'POST',
                data: 'start='+startDate+'&&end='+endDate,
                success: function(response){
                    var json_obj = $.parseJSON(response);
                    for(var i =0; i < json_obj.user.length; i++){
                        //What is the next?
                    }
                }
            });

Kindly help. 请帮助。 Thank you ! 谢谢 !

The json returned by jQuery is already a JavaScript object, not a string. jQuery返回的json已经是一个JavaScript对象,而不是字符串。 You do not have to parse it any further to use it. 您不必进一步解析它就可以使用它。 I'm on a mobile device right now so I can't confirm, but I'm pretty sure you can just do this: 我现在在移动设备上,因此无法确认,但是我很确定您可以这样做:

success: function(response){
    //try
    var name = response.user.name
    //try this as well
    var name = response.name
}

You should be able to print out the name string using console.log() after this. 之后,您应该可以使用console.log()打印出名称字符串。

I'm assuming that you're trying to convert some JSON in string form to an object usable by JS. 我假设您正在尝试将字符串形式的JSON转换为JS可用的对象。 You can parse a valid JSON string into a JS object by using JSON.parse(jsonString) . 您可以使用JSON.parse(jsonString)将有效的JSON字符串解析为JS对象。 (Where jsonString is a variable containing the string of JSON) (其中jsonString是包含JSON字符串的变量)

I suggest that you look over the jquery docs for more info, the best thing you can use is jquery.ajax Make sure that in your php script you encode the text as JSON, otherwise jquery will interpret it as plain/text. 我建议您查看jquery文档以获取更多信息,最好使用的是jquery.ajax确保在您的php脚本中将文本编码为JSON,否则jquery会将其解释为纯文本。

Little snippet, which you can also find on the jquery docs.. 小片段,您也可以在jquery文档中找到。

$.ajax( "example.php" )
.done(function(data) {
    console.log(data);
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM