json_en code产生畸形的JSON数据? [英] json_encode creating malformed JSON data?

查看:183
本文介绍了json_en code产生畸形的JSON数据?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个codeigniter应用程序从我的数据库返回一些数据的视图。我试图把它送回来的JSON数据。

I have a codeigniter application returns some data from my database to a view. I'm trying to send it back as json data.

的问题是,该被返回它的数据格式错误。 它看起来是这样的:

The problem is that the data that is returned it malformed. it looks like this:

 ({'2.5':"Admin1", '2.10':"Admin2"})

当我测试这个在jsonlint.com,它表明这是无效的JSON。 在2.5应该是在双引号,不是单引号。 我不明白的是,我号召我的数据json_en code之前,我把它传递给视图。我的code在我的控制器看起来是这样的:

When I test this on jsonlint.com, it shows that this is not valid json. the '2.5' should be in double quotes, not single quotes. What I don't understand is that I'm calling json_encode on my data before I pass it to the view. My code in my controller looks like this:

public function getbuildings()
{

        $buildings = array();
        $branchID = $this->uri->segment(3);
        $buildingforbranch = array();
        $_locations = $this->racktables_model->get_locations(); 
        //print_r($_locations);

        foreach ($_locations as $location)
        {
            if ((isset($location['L2FullID'])) && (!array_key_exists($location['L2FullID'],$buildings))) {
                $buildings[$location['L2FullID']] = $location['L2Location'];            
            }
        }

        foreach ($buildings as $key => $value)
        {

            $pattern = "/(".$branchID."\.\d)/i";            
            if (preg_match($pattern,$key))
            {
                $buildingforbranch[(string)$key] = $value;
            }

        }       
        header ('Content-Type: application/json; charset=UTF-8');
               echo json_encode($buildingforbranch);  

}

正如你可以从code看,我甚至试过明确铸造$关键字符串数据类型。但是,这似乎并没有改变任何东西。有什么建议么? 谢谢。

As you can see from the code, I've even tried casting $key explicitly to a string data type. But that doesn't seem to change anything. Any suggestions? Thanks.

修改1

当我做$ buildingforbranch一个变种转储前右页眉/ json_en code()调用,我得到如下结果:

When I do a var dump on $buildingforbranch right before the header / json_encode() calls, I get the following results:

array(3) {
  ["2.5"]=>
  string(7) "Admin 2"
  ["2.10"]=>
  string(7) "Admin 1"
  ["2.11"]=>
  string(3) "SB4"
}

这看起来不错,在这里......但是当我做的console.log(),并通过从控制器的数据,浏览器显示的格式不正确的JSON数据。

It looks good here ... but when I do a console.log() and pass in the data from the controller, the browser shows the incorrectly formed json data.

编辑2 这里就是我试图完成。我需要当用户点击我的网页上控制动态创建一个组合框。如果在一个空数组Ajax调用的结果,我不希望以显示组合。否则,我尝试填充组合框与AJAX调用的结果。一切正常,除了在那里我试图检查JSON数据的长度的一部分。不管是什么送回我的应用程序总是显示一个组合框。

EDIT 2 Here's what i'm trying to accomplish. I need to dynamically create a combo box when a user clicks on a control on my page. If the ajax call results in an empty array, I don't want to display the combo. Otherwise, I try to populate the combo box with the results of the ajax call. Everything is working, except for the part where I'm attempting to check the length of the json data. My app always displays a combo box regardless of what is sent back.

这里的code:

$.ajax({
                        url:"<?php echo site_url('switches/getbuildings/');?>" + "/" + $selectedvalue,
                        type:'GET',
                        dataType:'json',
                        success: function(returnDataFromController) {
                               console.log("getbuildings ajax call successfull");
                                var htmlstring;
                                htmlstring="<select name='L2Locations' id='L2Locations'>";
                                htmlstring = htmlstring + "<option value='all'>All</option>";

                                //console.log(returnDataFromController);
                                 var JSONdata=[returnDataFromController];
                                 console.log(JSONdata);
                                 if (JSONdata.length != 0) 
                                 {
                                        for(var i=0;i<JSONdata.length;i++){
                                        var obj = JSONdata[i];

                                                  for(var key in obj){
                                                         var locationkey = key;
                                                         var locationname = obj[key];
                                                         htmlstring = htmlstring + "<option value='" + locationkey + "'>" + locationname + "</option>";
                                                    } //end inner for


                                                $('#l2locations').html(htmlstring);

                                        }//end outer for
                                    }

                                    else {
                                        //alert('i think undefined');
                                        $('#l2locations').html('');
                                    }

                            }//success


                    });//end ajax

如果我调用直接返回JSON数据的页面,我得到[]作为结果的一个空数组。

If I call the page that is returning the json data directly, i get [] as the result for an empty array.

推荐答案

[]实际上是定义在您的特定情况下,单一元素的数组。但是,当我看到你在使用jQuery阿贾克斯与数据类型:JSON,这意味着返回的值已经是一个对象,你并不需要分析它多了一个时间,所以才删除[]:

[] is actually defines an array with a single element in your particular case. But as I see you are using jQuery ajax with dataType: "json", this means that the returned value is already an object, you don't need to parse it one more time, so just remove []:

var JSONdata=returnDataFromController; // instead of var JSONdata=[returnDataFromController];

这篇关于json_en code产生畸形的JSON数据?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆