Perl parse JSON response as an array - json

I have a long sql query with a lot of derived columns and I'm trying to get it displayed in an angular page. I reached the point where I'm getting a json response back from the db but its returning each row as one big object instead of an array. I'm using perl to query the db and I've tried a bunch of ways to parse it and I haven't gotten it yet.
The subroutine:
require fileWithAllImports.pl #has CGI, JSON, etc
%response = {};
$response{error}{code} = "0";
$response{error}{message} = "OK";
$sql = "select c.title as Content....";
$sql = &database_escape_sql($sql); #I think its self-explanatory what this does
%hash = &database_select_as_hash_with_auto_key(
$sql,"content ... "); #more columns
foreach $i ( keys %hash ) {
$id = $i;
$response{$i}{content} = $hash{$i}{content};
...
} #again all of the columns
print_json_response(%response);
The angular call:
$http.get("/folder/ofSubroutine.cgi")
.then(function(minutes_results) {
console.log(minutes_results);
and the json repsonse:
{"6":{"derivedcolumn":"123","anotherderived":"987",..},"11":{"derived column":"123"}...}
I believe ng-repeat only works with an array so how would I parse the response from the server into an array?

On the back end, you could place the data into a separate array instead of adding each row to the hash:
foreach $i ( keys %hash ) {
push #{$response{data}}, { id => $i,
content => $hash{$i}{content},
... ,
};
}
print_json_response( %response );
Or on the front end, convert your associative array to a regular array:
$http.get("/folder/ofSubroutine.cgi")
.then(function(minutes_results) {
console.log(minutes_results);
var minutes_results_as_array = [];
for (var key in minutes_results) {
if (key != "error") {
minutes_results[key].id = key;
minutes_results_as_array.push(minutes_results[key]);
}
}
// display minutes_results_as_array as you see fit
} );

Related

Can't iterate through JSON object

I'm pulling a JSON request from the politifact API:
request('http://politifact.com/api/v/2/statement/?format=[JSON]&order_by=-ruling_date&limit=1')
.then(({
data
}) => {
newArticles = extractListingsFromJSON(data);
and parsing it with a function that the JSON is passed to
function extractListingsFromJSON(json) {
var jsonObject = json.objects
Outputs entire objects array
var headline = jsonObject[0].facebook_headline
console.log("headline:\n" + headline)
Outputs headline from Objects[0]
This works as intended. However, when I try to iterate through the objects array like so:
for (var attr in jsonObject) {
console.log(attr+": "+jsonObject.facebook_headline);
}
Outputs "0: undefined"
I also tried:
console.log(attr+": "+jsonObject[facebook_headline];
Outputs nothing
As you mentioned yourself jsonObject is an array.
json.objects.forEach(function (i) {
console.log(i.facebook_headline)
})
You still need the attr key to iterate through the jsonObject. Try doing attr+" :"+jsonObject[attr].facebook_headline
instead.

Fat-Free-Framework / F3 access a hive variable in a mapper callback

I'm using the Fat Free Framework ORM Mapper functionality to insert a set of records passed from the client in an array. The Mapper function has callbacks to for aftersave which pass an array of keys and the mapper object.
I want to be able to loop through the records and use the mapper to insert the records one by one, storing the inserted record's id in an array ('resultsArray') which is set in the F3 hive in the parent function:
function myFunction (\Base $f3, $params) {
// array of records to insert
$mappedArray = json_decode( $f3->get('BODY'), true );
$f3->set('mapper', new mapper($db,'mytable'));
$mapper = $f3->get('mapper');
// create an array in the hive to store the results of the inserts
$f3->set('resultsArray', array());
// set mapper callbacks
$mapper->aftersave(function($self,$pkeys){
// update the resultsArray in the hive?
});
$recordsInArray = count($mappedArray);
// loop through the array of objects
for ($loop = 0; $loop<$recordsInArray; $loop++){
$newRecord = $mappedArray[$loop];
try{
// clear the mapper down
$mapper->reset();
// set the array in the hive
$f3->set('data', $newRecord );
$mapper->copyFrom('data');
$mapper->save();
} catch(\PDOException $e) {
// do something
exit;
}
}
echo "done";
}
Is there a way to access the resultsArray variable I set in the hive in the aftersave callback?
Thanks
Matt
Are you sure that you need to do all these things to achieve what you want?
To be able to store the IDs of inserted records and put it in the F3's hive, I would do the following:
<?php
function myFunction (\Base $f3, $params) {
// array of records to insert
$mappedArray = json_decode( $f3->get('BODY'), true );
//mapper (no need to put it into hive):
$mapper = new mapper($db,'mytable');
// array with IDs:
$resultsArray = [];
// loop through the array of objects
for ($loop = 0; $loop<count($mappedArray); $loop++){
try{
// clear the mapper down
$mapper->reset();
// map the content (no need to put it in the hive):
$mapper->copyFrom($mappedArray[$loop]);
// insert new record:
$mapper->save();
// get the ID of the inserted record and put it in the array:
$resultsArray[] = $mapper->_id;
} catch(\PDOException $e) {
// do something
exit;
}
}
// put the array of IDs in the hive:
$f3->set("newIDs", $resultsArray);
}
You can access the hive within the aftersave handler with the php use feature:
function myFunction (\Base $f3, $params) {
// ...
$mapper->aftersave(function($self,$pkeys) use($f3) {
$f3->get('resultsArray');
});
}

json C# 7 Tuple Support

I want to get my C#7 tuple property names in my JSON (Newtonsoft.Json) output.
My problem is:
When I want to convert my tuple to JSON format that not support my parameters names.
For example this is my "Test2" method and you can see the JSON output:
public void Test2()
{
var data = GetMe2("ok");
var jsondata = JsonConvert.SerializeObject(data);//JSON output is {"Item1":5,"Item2":"ok ali"}
}
public (int MyValue, string Name) GetMe2(string name)
{
return (5, name + " ali");
}
The JSON output is "{"Item1":5,"Item2":"ok ali"}" but i want "{"MyValue":5,"Name":"ok ali"}";
This is not impossible because I can get property names in runtime:
foreach (var item in this.GetType().GetMethods())
{
dynamic attribs = item.ReturnTypeCustomAttributes;
if (attribs.CustomAttributes != null && attribs.CustomAttributes.Count > 0)
{
foreach (var at in attribs.CustomAttributes)
{
if (at is System.Reflection.CustomAttributeData)
{
var ng = ((System.Reflection.CustomAttributeData)at).ConstructorArguments;
foreach (var ca in ng)
{
foreach (var val in (IEnumerable<System.Reflection.CustomAttributeTypedArgument>)ca.Value)
{
var PropertyNameName = val.Value;
Console.WriteLine(PropertyNameName);//here is property names of C#7 tuple
}
}
}
}
dynamic data = attribs.CustomAttributes[0];
var data2 = data.ConstructorArguments;
}
}
For the specific case here, it is impossible. That's because SerializeObject has no way of finding out where the tuple came from, all it sees is ValueTuple<int, string>.
The situation would be different if you were serializing an object with tuple properties, in which case SerializeObject could use reflection to find the TupleElementNames attributes (even though it currently doesn't).
The short answer it that tuples don't have properties.
A tuple is a bag of values used, mainly, to return multiple values from a method.
They were never intended to model entities.
The only way to solve your problem, if you don't want to create a type for that, is:
public void Test2()
{
var data = GetMe2("ok");
var jsondata = JsonConvert.SerializeObject(new { data.MyValue, data.Name });//JSON output is {"Item1":5,"Item2":"ok ali"}
}

Using AJAX returned JSON encoded data in Codeigniter

I am relatively new to codeigniter. While I was trying to perform a searching operation on my data base using AJAX, The code is returned as successful and the data is retrieved but, This data is JSON encoded and is in the javascript portion of my view so I am unable to use the json_decode function of codeigniter
public function lookup(){
$keyword = $this->input->post('term');
$data['response'] = 'false'; //Set default response
$query = $this->MAutocomplete->lookup($keyword); //Search DB
if( ! empty($query) )
{
$data['response'] = 'true'; //Set response
$data['message'] = array(); //Create array
foreach( $query as $row )
{
$data['message'][] = array(
'id'=>$row->id,
'value' => $row->firstname,
); //Add a row to array
}
}
echo json_encode($data); //echo json string
}
the data is accessed in the javascript as data.message.
Please tell me is there anyway i can use this data in the php part of my program
<?php
class MAutocomplete extends CI_Model{
function lookup($keyword){
$this->load->database();
$this->db->select('*');
$this->db->from('Students');
$this->db->like('firstName',$keyword,'after');
$query = $this->db->get();
// echo '<pre>'; print_r($query->result()); exit;
return $query->result();
}
}
I think you need to parse json response in Ajax's success function using JSON.parse().Like this..
$.ajax({
url:'',//your url
dataType:'JSON',
data:'',//your data
success:function(response){
data = JSON.parse(response);
alert(data.message.value);//alerts value
}
});
In controller use count rather than empty.To check the array
if( count($query) >0 )
{
$data['response'] = 'true'; //Set response
$data['message'] = array(); //Create array
foreach( $query as $row )
{
$data['message'][] = array(
'id'=>$row->id,
'value' => $row->firstname,
); //Add a row to array
}
}
You should use to response:
return $this->output
->set_content_type('application/json')
->set_output(json_encode($data));

Convert codeigniter query to json?

I want to convert a model query to json with json_encode, it doesn't work. But with a ordinary array it does.
$arr = array("one", "two", "three");
$data["json"] = json_encode($arr);
Output
<?php echo "var arr=".$json.";"; ?>
var arr=["one","two","three"];
But when I try to convert a query codeigniter throws an error. What is it with that?
This is the error message:
A PHP Error was encountered Severity:
Warning Message: [json]
(php_json_encode) type is unsupported,
encoded as null
And the converted "query" result = I mean model method is like this:
{"conn_id":null,"result_id":null,"result_array":[],"result_object":[],"current_row":0,"num_rows":9,"row_data":null}
I try to do like this
$posts = $this->Posts_model->SelectAll();
$data["posts"] = json_encode($posts);
By the way, the model and method works just fine when I do it without json_encode.
Something I'm propably doing wrong, but the question is what?
You appear to be trying to encode the CodeIgniter database result object rather than the result array. The database result object acts as a wrapper around the cursor into the result set. You should fetch the result array from the result object and then encode that.
Your model code appears to be something like this :
function SelectAll()
{
$sql = 'SELECT * FROM posts';
// Return the result object
return $this->db->query($sql);
}
It should be more like this :
function SelectAll()
{
$sql = 'SELECT * FROM posts';
$query = $this->db->query($sql);
// Fetch the result array from the result object and return it
return $query->result();
}
This will return an array of objects which you can encode in JSON.
The reason you are getting an error trying to encode the result object is because it has a resource member variable that cannot be encoded in JSON. This resource variable is actually the cursor into the result set.
public function lastActivity()
{
header("Content-Type: application/json");
$this->db->select('*');
$this->db->from('table_name');
$query = $this->db->get();
return json_encode($query->result());
}
As per latest CI standard use the following code in your controller file:
$this->output->set_content_type('application/json')->set_output(json_encode($arr));
Models (Post):
function SelectAll()
{
$this->db->select('*');
$this->db->from('post');
$query = $this->db->get();
return $query;
}
Controllers :
$data['post'] = $this->post->SelectAll()->result_array();
echo json_encode($data);
Result:
{"post":[{"id":"5","name":"name_of_post"}]}
Here is the working solution:
$json_data = $this->home_model->home_getall();
$arr = array();
foreach ($json_data as $results) {
$arr[] = array(
'id' => $results->id,
'text' => $results->name
);
}
//save data mysql data in json encode format
$data['select2data'] = json_encode($arr);