Does Json_encode generate invalid JSON data?

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

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

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

When I test this on jsonlint.com, it shows that it is not valid json. "2.5" must be in double quotation marks, not single quotation marks. I do not understand that I am calling json_encode in my data before passing it to the view. My code in my controller is as follows:

 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); } 

As you can see from the code, I even tried explicitly calling $ key a string data type. But it does not change anything. Any suggestions? Thank you

EDIT 1

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

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

It looks good here ... but when I do console.log () and transfer data from the controller, the browser shows json data that is not properly formed.

EDIT 2 This is what I am 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 combos. Otherwise, I am trying to populate a combo box with the results of an ajax call. Everything works, except for the part where I try to check the length of json data. In my application, a combo box is always displayed no matter what is sent back.

Here is the 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 

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

+3
source share
3 answers

[] actually defines a single element array in your particular case. But, as I see it, you are using jQuery ajax with dataType: "json" , this means that the return value is already an object, you do not need to parse it again, so just delete []:

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

As pointed out in your other question , you need to handle JSON as JSON.

The main review:

  • returnDataFromController will be a string, use JSON.parse() or jQuery parseJson () to convert it to a JSON object
  • Rewrite your loop, which generates parameters to iterate over the JSON object instead of an array. Please note that jquery.each () can process both arrays and objects . This seems to be the part you are missing.

The real key here is holding data types straight. You get a back row containing JSON data. There is no easy way to convert this to an array, so read it as JSON. Since this is now a JSON object, you should consider it as a JSON object, not an array.

Check out jQuery Utilities for other JSON related items.

0
source

Use firebug on firefox to see what is shown on the answer tab on the net tab
This code

 <?php echo json_encode(array( "2.5" => "Admin 2", "2.10" => "Admin 1", "2.11" => "SB4" )); 

produces this output {"2.5":"Admin 2","2.10":"Admin 1","2.11":"SB4"} on my server (php5.3) and in this example script http: //www.phpfiddle .org / main / code / xqy-ize

0
source

Source: https://habr.com/ru/post/948545/


All Articles