How to iterate JSON with Laravel in Blade - json

I am starting to use Mongo with Laravel. I have managed to make the connection and execute the first added queries.
The question I have now is to iterate through the results with foreach in the blade template.
I go through a basic json file without problems
$json1 = '{
"title":"Superman",
"category": "Superhero"
}';
return view('index', ['data' => $json1]);
On the blade:
#foreach($data as $item)
{{$item->title}}
{{$item->category}}
<br/>
#endforeach
Now, how do I go through the following file:
$json2 = '{
"tag":{
"title":"title"
}
}';
return view('index')->with('data', json_decode($json2));
I don't know how to access the title of the tag.
I have tried the following but without success.
#foreach($data as $item)
{{$item->tag.title}}
<br/>
#endforeach

The json_decode method returns a stdClass object (unless you provide true as the second parameter which returns an associative array).
So once you have decoded your JSON, you can access the properties as you would do so for any other class based property:
$json2 = '{
"tag":{
"title":"title"
}
}';
$data = json_decode($json2);
return view('index', compact('data'));
#foreach ($data as $item)
{{ $item->title }}
#endforeach

Related

Perl HTTP Tiny response

How to put the JSON response of HTTP::Tiny in Perl?
use HTTP::Tiny;
my $response = HTTP::Tiny->new->get('http://example.com/');
die "Failed!\n" unless $response->{success};
print "$response->{status} $response->{reason}\n";
while (my ($k, $v) = each %{$response->{headers}}) {
for (ref $v eq 'ARRAY' ? #$v : $v) {
print "$k: $_\n";
}
}
print $response->{content} if length $response->{content};
How to put the $response->{content} into variable to be passed into html(tt2)?
You would pass your content to the TT processor like this:
use Template;
my $tt = Template->new;
$tt->process('some_template.tt', { content => $response->{content} })
or die $tt->error;
Perhaps you want to store it in an intermediate scalar first:
my $content = $response->{content};
$tt->process('some_template.tt', { content => $content })
or die $tt->error;
Perhaps you want to build up TT's variable hash before passing it to the processor.
my %vars;
$vars{content} = $response->{content};
$tt->process('some_template.tt', \%vars)
or die $tt->error;
Or you could use a hash reference instead of an actual hash:
my $vars;
$vars->{content} = $response->{content};
$tt->process('some_template.tt', $vars)
or die $tt->error;
Update: In a comment, simbabque suggests that you might actually be asking how to decode JSON content into an array or a hash. And I agree that's another way to interpret your question.
You'd need to use the JSON module. And it would look something like this:
use JSON;
my $json_parser = JSON->new; # Perhaps other options here, see docs.
my $decoded_json = $json_parser->decode($response->{content});

invalid json response in php when json response inside json response

i have try to print json response but "" are added to my json response
i tried below code php and id generated by drupal field
<?php
$data = array("title"=>"test","body"=>"test body");
$php = json_encode($data,JSON_FORCE_OBJECT);
echo json_encode(array("php"=>$php,"id"=>10));
?>
output :
{"php":"{\"title\":\"test\",\"body\":\"test body\"}","id":10}
but i want output like below
{"php":{"title":"test","body":"test body"},"id":10}
i added some more code for above problem
{"php":"{\"title\":\"test\",\"body\":\"test body\"}","id":10}
why not remove json_encode from echo json_encode($php);
how i can get above output` second time
You're encoding in JSON two times :
$data = array("title"=>"test","body"=>"test body");
$php = json_encode($data,JSON_FORCE_OBJECT);
echo $php ; // remove json_encode() here
After question edit:
$data = array("title"=>"test","body"=>"test body");
echo json_encode(array("php"=>$data,"id"=>10));
You can also simply do this,
<?php
$data = array("title"=>"test","body"=>"test body");
echo json_encode(array("php"=>$data,"id"=>10));
?>

Processing results from fatfree DB SQL Mapper for json encoding

I'm having trouble processing the returned results from a DB SQL Mapper into a recognizable json encoded array.
function apiCheckSupplyId() {
/*refer to the model Xrefs*/
$supply_id = $this->f3->get('GET.supply_id');
$xref = new Xrefs($this->tongpodb);
$supply = $xref->getBySupplyId( $supply_id );
if ( count( $supply ) == 0 ) {
$this->logger->write('no xref found for supply_id=' .$supply_id);
$supply = array( array('id'=>0) );
echo json_encode( $supply );
} else {
$json = array();
foreach ($supply as $row){
$item = array();
foreach($row as $key => $value){
$item[$key] = $value;
}
array_push($json, $item);
}
$this->logger->write('xref found for supply_id=' .$supply_id.json_encode( $json ) );
echo json_encode( $json );
}
}
This is the method I am using but it seems very clunky to me. Is there a better way?
Assuming the getBySupplyId returns an array of Xref mappers, you could simplify the whole thing like this:
function apiCheckSupplyId() {
$supply_id = $this->f3->get('GET.supply_id');
$xref = new Xrefs($this->tongpodb);
$xrefs = $xref->getBySupplyId($supply_id);
echo json_encode(array_map([$xref,'cast'],$xrefs));
$this->logger->write(sprintf('%d xrefs found for supply_id=%d',count($xrefs),$supply_id));
}
Explanation:
The $xrefs variable contains an array of mappers. Each mapper being an object, you have to cast it to an array before encoding it to JSON. This can be done in one line by mapping the $xref->cast() method to each record: array_map([$xref,'cast'],$xrefs).
If you're not confident with that syntax, you can loop through each record and cast it:
$cast=[];
foreach ($xrefs as $x)
$cast[]=$x->cast();
echo json_encode($cast);
The result is the same.
The advantage of using cast() other just reading each value (as you're doing in your original script) is that it includes virtual fields as well.

JSON string and PERL

How can I read a JSON string like this without "headers":
[{"SMS":"hello","NUM":12345},{"SMS":"bye","NUM":54321}]
my $json = JSON->new->utf8;
my $perl_data = $json->decode($content);
print ref($perl_data) . "\n";
returns ARRAY. I would like each element.
Thanks
There is an array ref around the hash references. You need to iterate over the array reference to get each element.
use Data::Dumper;
foreach my $elem (#{ $perl_data }) {
print Dumper $elem;
}

How to parse JSON/REST data from server using Perl

Im trying to parse out JSON output from the server using Perl. The connection and downloading of the REST data is ok, I just need help parsing the returned data. Here is the snippet for my code:
my $response = HTTP::Tiny->new->get($SERVER_ADDR);
if ($response->{success})
{
my $html = $response->{content};
#LINES = split /\n/, $html;
chomp(#LINES);
print("Lines: '#LINES'\n"); # ZZZ
my $decoded_json = decode_json( $html );
print Dumper $decoded_json;
}
else
{
print "Failed: $response->{status} $response->{reasons}";
}
And here is the results:
Lines: '{"players":[{"currentlyOnline":false,"timePlayed":160317,"name":"MarisaG","lastPlayed":1474208741470}]}'
$VAR1 = {
'players' => [
{
'currentlyOnline' => bless( do{\(my $o = 0)}, 'JSON::PP::Boolean' ),
'timePlayed' => 160317,
'lastPlayed' => '1474208741470',
'name' => 'MarisaG'
}
]
};
There will be multiple entries under the "players" for each player logged in right now. Any tips?
I'm not really sure what you're asking. You have successfully parsed the JSON by by calling decode_json(). You now have a data structure in $decoded_json. Your call to Dumper() shows the structure of that data. It's a hash reference with a single key, players. The value associated with that key is an array reference. Each element in the referenced array is another hash.
So, for example, you could print all of the players' names with code like this.
foreach (#{ $decoded_json->{players} }) {
say $_->{name};
}