unable to parse json property - json

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

Related

How to create object from arrays of row in laravel Elequent

Here I want to make the array inside "property" to an object where the key of the object will be the value of 'key_name' column of product_property table
[{
"sort_order": 1,
"name": "Samosas",
"visible": 1,
"description": null,
"property": [
{
"product_uuid": "95be9cf4-7121-492b-8725-762e6353ac51",
"key_name": "categories",
"key_value": "Starter"
},
{
"product_uuid": "95be9cf4-7121-492b-8725-762e6353ac51",
"key_name": "print_order",
"key_value": "1"
}
]
}]
This is what I want
[{
"sort_order": 1,
"name": "Samosas",
"visible": 1,
"description": null,
"property": {
"categories": "Starter",
"print_order": "1"
}
}]
I tried with Product::with('property')->get() and it results the first array.
Is there any Eloquent way to do that or raw sql or Query Builder?
Looping throw the result and make that object is possible but here i want something from SQL end
$products = Product::with('property')->get();
foreach ($products as $product) {
$array = [];
foreach ($product->property as $property) {
$array[$property['key_name']] = $property['key_value'];
}
$product->properties = $array;
}
This looping giving me the results but its from php end
public function property(){
return $this->hasMany(ProductProperty::class, 'product_uuid', 'uuid');
}
The Product model
Product table
"sort_order",
"name",
"visible",
"description",
Product Property table
"product_uuid",
"key_name",
"key_value"
Thanks in advance
$products = Product::with('property')->get();
foreach ($products as $product) {
$array = [];
foreach ($product->property as $property) {
$array[$property['key_name']] = $property['key_value'];
}
$product->properties = (object) $array;
}
Add object. It will convert this to a std object.

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'

Json response in Codeigniter

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

Echo a specific values of a json

Currently working with this sort of json:
[
{
"title": "Ramones",
"authors": {
"6172": {
"lastname": "Ramone",
"firstname": "Joey",
},
"6768": {
"lastname": "Ramone",
"firstname": "Dee Dee",
}
}
}
]
And would like to display values as this:
Ramones Joey Ramone Dee Dee Ramone
The PHP code i use:
$arr = json_decode(file_get_contents("my-json-url"),true);
foreach($arr as $item) {
echo "<h1>".$item['title']."</h1>";
echo .$item['authors']['firstname'].$item['authors']['lastname'];
};
And as result i only get the title value, didn't know how to pass through the ID number.
Thanks for your help.
You can use a second foreach loop to loop through the authors of your item :
$arr = json_decode(file_get_contents("my-json-url"),true);
foreach($arr as $item) {
echo "<h1>".$item['title']."</h1>";
foreach($item['authors'] as $author)
{
echo "\n".$author['firstname']." ".$author['lastname'];
}
};
I also improved the authors output, so you get the wanted display.

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).'}';
?>