Json response in Codeigniter - json

Below is the code for user list webservice's json response.
<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');
class Webservice extends CI_Controller
{
function list_user()
{
$result_login = $this->db->get('user_registration')->result();
$response = array();
$response ["success"] = 1;
$response ["message"] = "User List.";
foreach($result_login as $row)
{
$data = array();
$data['User Id'] = $row->user_id;
$data['Name'] = $row->name;
$data['Email'] = $row->email;
$data['mobile_number'] = $row->mobile_number;
$data['Password'] = $row->password;
$output2 = json_encode(array('responsedata' => $data));
echo $output2;
}
}
}
?>
In my code if i replace $data with $response in json_encode then i can't get $data's value.
I got json response in this format. JSON Response.
{
"responsedata": {
"User Id": "7",
"Name": "bhavin",
"Email": "bhavin123#gmail.com",
"mobile_number": "123456789",
"Password": "abc"
}
}
But i want json response in this format.
{
"responsedata":
{
"success": 1,
"data": [
{
"User Id": "7",
"Name": "test",
"Email": "test1#gmail.com",
"mobile_number": "123456789",
"Password": "abc"
},
{
"User Id": "8",
"Name": "test2",
"Email": "test2#gmail.com",
"mobile_number": "123456789",
"Password": "abc"
}
]
}
}

You need to arrange Your array like this
I update below code
$array_of_event = array()
foreach($result_login->result_array() as $row)
{
$array_of_event[] = $row;
}
$data['success'] = "1";
$data['data'] = $array_of_event; //need to assign event here
$response['responsedata'] = $data;
echo json_encode($response);

Related

Determine depth of object &/or JSON values using PowerShell Loop

I am using an api to gather a list of comments for particular tickets, the tickets have nested comments which are returned from the api like so:
{
"comments": [
{
"text": "test 1",
"comments": [
{
"text": "test 2",
"comments": [
{
"text": "test 3",
"comments":[]
}
]
}
]
}
]
}
The number of child comments can be n for any parent comment. I'm ultimately trying to get the text value for each "comments" tag until the "comments" tag is null.
I thought about making a parent object then trying to append the property search until it returns null.
$n = 1
$exists = $true
while ($exists){
$string = ".comments"
$search = $string * $n
$search = $search.Substring(1)
$m = $i.$search
$commentVal = $m.comments
$textValue = $m.text
$textValue
if ($textValue -ne ''){
$comments += $textValue
}
if ($commentVal){
$exists = $true
}else{
$exists = $false
}
$n++
}
This does work but only for one iteration. i.e. if $search = "comments.comments" $i.$search does not work, but $search = "comments"; $i.$search does work.
Here's a solution for you that converts the response to an object and recurses on the comments property:
$rawJson = #'
{
"comments": [
{
"text": "test 1",
"comments": [
{
"text": "test 2",
"comments": [
{
"text": "test 3",
"comments":[]
}
]
}
]
}
]
}
'#
$jsonObj = $rawJson | ConvertFrom-Json
$comment = $jsonObj.Comments
$allComments = while ($null -ne $comment) {
$comment.text
$comment = $comment.Comments
}
Edit
(a bit of explanation might be helpful)
if $search = "comments.comments" $i.$search does not work, but $search = "comments"; $i.$search does work.
This is expected, if not intuitive. $i.comments tells PowerShell to index on the comments property, and $i.comments.comments tells it to do twice.
Problem is when using a variable like in the case $search = "comments.comments", $search is not expanded; PowerShell will look for the literal property comments.comments.
Try your code on this json:
{
"comments": [
{
"text": "test 1",
"comments": [
{
"text": "test 2",
"comments": [
{
"text": "test 3",
"comments":[]
}
]
}
]
}
],
"comments.comments": [
{
"text": "test 2.0",
"comments": [
{
"text": "i'm not empty"
}
]
}
],
"comments.comments.comments": [
{
"text": "test 3.0",
"comments": [
{
"text": "i'm not empty"
}
]
}
]
}

JSON to text, special sequence

I want to create a text document from following JSON document:
[
{
"id": 12345,
"url": "https://www.w3schools.com",
"person": {
"firstname": "John",
"lastname": "Doe"
},
"department": "IT"
},
{
"id": 12346,
"url": "https://www.w3schools.com",
"person": {
"firstname": "Anna",
"lastname": "Jackson"
},
"department": "LOG"
}
]
My JSON schema looks like the following:
{
"type": "array",
"items": {
"type": "object",
"properties": {
"id": { "type": "integer" },
"url": { "type": "string", "format": "uri" },
"person": {
"type": "object",
"properties": {
"firstname": { "type": "string" },
"lastname": { "type": "string" }
}
},
"department": { "enum": [ "IT", "LOG"] }
}
}
}
The text document should be structured as follows:
pid: 12345
dep-abb: IT
surname: Doe
name: John
pid: 12346
dep-abb: LOG
surname: Jackson
name: Anna
I'm a Perl and JSON newbie and was searching for a Perl lib that can handle this approach by extending the schema (e.g. by txt_seq_no and txt_label). The labels in the text file should be sorted by txt_seq_no ASC and renamed by txt_label. Is is possible to solve that issue that simple? Then the schema could look like:
{
"type": "array",
"items": {
"type": "object",
"properties": {
"id": { "type": "integer", "txt_seq_no"=10, "txt_label"="pid" },
"url": { "type": "string", "format": "uri" },
"person": {
"type": "object",
"properties": {
"firstname": { "type": "string", "txt_seq_no"=40, "txt_label"="name" },
"lastname": { "type": "string", "txt_seq_no"=30, "txt_label"="surname" }
}
},
"department": { "enum": [ "IT", "LOG", "PROD" ], "txt_seq_no"=20, "txt_label"="dep-abb" }
}
}
}
The basic approach is to use a JSON module to decode the JSON into a Perl data structure and then walk that structure to construct the output that you want.
#!/usr/bin/perl
use strict;
use warnings;
use feature 'say';
use JSON;
my $json = JSON->new;
my $json_str = '[
{
"id": 12345,
"url": "https://www.w3schools.com",
"person": {
"firstname": "John",
"lastname": "Doe"
},
"department": "IT"
},
{
"id": 12346,
"url": "https://www.w3schools.com",
"person": {
"firstname": "Anna",
"lastname": "Jackson"
},
"department": "LOG"
}
]';
my $data = $json->decode($json_str);
for (#$data) {
say "pid: $_->{id}";
say "dep-abb: $_->{department}";
say "surname: $_->{person}{lastname}";
say "name: $_->{person}{firstname}\n";
}
Thanks all for tips and support!
I'm a totally beginner in Perl, feedback is welcome!
(I've ommited function parameter check to save space)
used packages:
use Data::Traverse;
use Data::Path;
sub transform
# key identifier[0]: mark JSON key that write into text file
# key identifier[1]: optional in JSON schema: new label in text file
my #KEY_IDENTIFIER = ("txt_seq_no", "txt_label");
# keys in JSON SCHEMA, can not be found in JSON document
my #DELETE_FROM_PATH = ( "items", "properties" );
# transform a JSON document into text file
# use identifier in JSON schema to define keys to transform to text
sub transform {
my ( $doc, $schema, $key_identifier) = #_;
if( not defined $key_identifier ) { $key_identifier = \#KEY_IDENTIFIER; }
my $transformator = get_transformator4schema( $schema, $key_identifier, $log );
my $data = get_data4transformator( $doc, $transformator, $log );
print_text( $data, $transformator, $key_identifier, $log );
}
sub get_transformator4schema
sub get_transformator4schema {
my ( $schema, $key_identifier) = #_;
my $t= Data::Traverse->new( $schema);
my %transformator;
$t->traverse(
sub {
if( $t->item_key eq #{$key_identifier}[0] or $t->item_key eq #{$key_identifier}[1]) {
my $path = $t->path;
my $key;
# delete path that only exists in schema, not in doc
foreach my $del_path (#DELETE_FROM_PATH) {
$path =~ s/\/$del_path//g;
}
# delete last element from path
if( $t->item_key eq #{$key_identifier}[0]) {
$key = #{$key_identifier}[0];
$path =~ s/\/#{$key_identifier}[0]$//g;
}
if( $t->item_key eq #{$key_identifier}[1]) {
$key = #{$key_identifier}[1];
$path =~ s/\/#{$key_identifier}[1]$//g;
}
# add key => { key => value }
if( not exists $transformator{$path} ) {
my %key_val = ( $key => $_ );
$transformator{$path} = \%key_val;
} else {
my $nested_hash = $transformator{$path};
$nested_hash->{$key} = $_;
}
}
}
);
return \%transformator;
}
sub get_data4transformator
# fetch needed data from document
sub get_data4transformator {
my ( $document, $transformator, $log ) = #_;
my #template;
foreach my $doc (#{$document}) {
my $doc_path= Data::Path->new( $doc );
my %th = ();
# load values for key = path
foreach my $path (keys %{$transformator}) {
my $val = $doc_path->get($path);
# add value from doc to hash
$th{$path} = $val;
}
push #template, \%th;
}
return \#template;
}
sub print_text:
sub print_text {
my ( $data, $transformator, $key_ids, $log ) = #_;
# sort by 1st item of $key_ids
my $sort_by = #{$key_ids}[0];
my $opt_name = #{$key_ids}[1];
print "\nsort data by '$sort_by' ASC\n";
my #sorted_keys = sort {
$transformator->{$a}->{$sort_by}
<=>
$transformator->{$b}->{$sort_by}
} keys %{$transformator};
foreach my $tdoc ( #{$data} ) {
print "\nread document item:\n";
foreach my $key ( #sorted_keys ) {
my $name = $key;
$name =~ s/^.*\/(\w+)$/$1/g;
my $alias_name = "";
if( defined $transformator->{$key}->{$opt_name} ) {
$alias_name = $transformator->{$key}->{$opt_name};
}
print " $name => $tdoc->{$key}";
if( not $alias_name eq "" ) {
print " alias '$alias_name'\n";
} else {
print "\n";
}
}
}
}
This functionality allows to control which key goes into the text file and its position. With at least one parameter txt_seq_no. The second parameter txt_label is optional and stores the alternative label in the textfile.
output:
id => 12345 alias 'pid'
department => IT alias 'dep-abb'
lastname => Doe
firstname => John alias 'name'
id => 12346 alias 'pid'
department => LOG alias 'dep-abb'
lastname => Jackson
firstname => Anna alias 'name'
id => 12347 alias 'pid'
department => PROD alias 'dep-abb'
lastname => Smith
firstname => Peter alias 'name'

Using a custom function in a Laravel 5 Controller

I'm using a Laravel 5, I just want to know how to use or declare a custom function inside my controller. I have
class UploadController extends Controller
{
function on_request_done($content, $url, $ch, $search) {
$httpcode = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($httpcode !== 200) {
print "Fetch error $httpcode for '$url'\n";
return;
}
$responseobject = json_decode($content, true);
if (empty($responseobject['responseData']['results'])) {
print "No results found for '$search'\n";
return;
}
print "********\n";
print "$search:\n";
print "********\n";
$allresponseresults = $responseobject['responseData']['results'];
foreach ($allresponseresults as $responseresult) {
$title = $responseresult['title'];
print "$title\n";
}
}
}
And whenever I call on_request_done inside one of my functions let's say,
public function getParallelApi()
{
define ('SEARCH_URL_PREFIX', 'http://ajax.googleapis.com/ajax/services/search/web?v=1.0&rsz=large&filter=0');
$terms_list = array(
"John", "Mary",
"William", "Anna",
"James", "Emma",
"George", "Elizabeth",
"Charles", "Margaret",
"Frank", "Minnie",
"Joseph", "Ida",
"Henry", "Bertha",
"Robert", "Clara",
"Thomas", "Alice",
"Edward", "Annie",
"Harry", "Florence",
"Walter", "Bessie",
"Arthur", "Grace",
"Fred", "Ethel",
"Albert", "Sarah",
"Samuel", "Ella",
"Clarence", "Martha",
"Louis", "Nellie",
"David", "Mabel",
"Joe", "Laura",
"Charlie", "Carrie",
"Richard", "Cora",
"Ernest", "Helen",
"Roy", "Maude",
"Will", "Lillian",
"Andrew", "Gertrude",
"Jesse", "Rose",
"Oscar", "Edna",
"Willie", "Pearl",
"Daniel", "Edith",
"Benjamin", "Jennie",
"Carl", "Hattie",
"Sam", "Mattie",
"Alfred", "Eva",
"Earl", "Julia",
"Peter", "Myrtle",
"Elmer", "Louise",
"Frederick", "Lillie",
"Howard", "Jessie",
"Lewis", "Frances",
"Ralph", "Catherine",
"Herbert", "Lula",
"Paul", "Lena",
"Lee", "Marie",
"Tom", "Ada",
"Herman", "Josephine",
"Martin", "Fanny",
"Jacob", "Lucy",
"Michael", "Dora",
);
if (isset($argv[1])) {
$max_requests = $argv[1];
} else {
$max_requests = 10;
}
$curl_options = array(
CURLOPT_SSL_VERIFYPEER => FALSE,
CURLOPT_SSL_VERIFYHOST => FALSE,
CURLOPT_USERAGENT, 'Parallel Curl test script',
);
$parallel_curl = new ParallelCurl($max_requests, $curl_options);
foreach ($terms_list as $terms) {
$search = '"'.$terms.' is a"';
$search_url = SEARCH_URL_PREFIX.'&q='.urlencode($terms);
$parallel_curl->startRequest($search_url, 'on_request_done', $search);
}
$parallel_curl->finishAllRequests();
//return "Helloo";
}
I get
call_user_func() expects parameter 1 to be a valid callback, function 'on_request_done' not found or invalid function name
My route
Route::get('/parallelapi', 'UploadController#getParallelApi');
PLEASE NOTE THAT getParallelApi() is under UploadController as well.
The problem is you are passing in the name of the function but it has no idea what class that function exists in. You should be able to do this by passing an array as your callback with the first item being an instance of your controller and the second item being the name of the function.
$parallel_curl->startRequest($search_url, [$this, 'on_request_done'], $search);

unable to parse json property

I'm trying to get the value of username and id from the following output.
{
"listusersresponse": {
"count": 1,
"user": [
{
"id": "f01e8ea4-2da5-11e4-a846-726c7bbb864f",
"username": "admin",
"firstname": "admin",
"lastname": "test",
"created": "2014-08-26T20:52:24-0400",
"state": "enabled",
"account": "admin",
"accounttype": 1,
"domainid": "c091153a-2da5-11e4-a846-726c7bbb864f",
"accountid": "f01e7c02-2da5-11e4-a846-726c7bbb864f",
"iscallerchilddomain": false,
"isdefault": true
}
]
}
}
This is what I have tried
$url = file_get_contents("http://URL/client/&response=json");
$data = json_decode($url);
var_dump($data);
foreach ($data as $value) {
echo $value->count;
}
For this works and I get 1
However when trying to access "username"
foreach ($data as $value) {
echo $value->user->username;
}
I get the following error: Notice: Trying to get property of non-object in "filename"
User is an array.
foreach ($data as $value) {
echo $value->user[0]->username;
}
Not sure how your json looks with several users, It must be like this then I guess:
foreach ($data as $value) {
foreach ($value->user as $user) {
echo $user->username;
}
}

JSON parse MySQL field with JSON inside

sorry if this is a dumb question. My problem is I want make a PHP file that parses in JSON the contents of a MySQL table. The problem is i have a field that have JSON in it with breaklines:
{
"6cb20a9f-27fa-4d98-ac2e-e959eb3f0f63": {
"file": "",
"title": "",
"link": "",
"target": "0",
"rel": ""
},
"43aa1b15-986e-4303-afcf-628b835f10e5": {
"0": {
"value": "<p>This is an example description.<\/p>"
}
},
"97dacf42-398b-45c5-8536-baec4250b27e": {
"0": {
"value": "2012-10-19 00:00:00"
}
},
"20fec805-ebb1-4045-9f3d-ea90ad952e91": {
"0": {
"value": "A restaurant"
}
}
}
So at the moment of using the PHP it looks like this:
PHP Fail
What can I do for it to avoid the \n and \t, because I'm sending this parse to an iphone app and it doesn't recognize it. Thanks!
The PHP Code is something like this:
<?php>
$link = mysql_pconnect("localhost", "root", "") or die("Could not connect");
mysql_select_db("test") or die("Could not select database");
$arr = array();
$rs = mysql_query("SELECT * FROM people");
while($obj = mysql_fetch_object($rs)) {$arr[] = $obj;
}
echo '{"members":'.json_encode($arr).'}';
?>