How to create a json file in laravel to store data in json format so that I can use it in ajax coz I'm having problem in autocomplete search. I have done this but it worked in Category not in item.
$catagories=Catagory::where('status',1)->get(['name'])->toArray();
$items=Item::where('status',1)->get()->toArray();
$cats=array();
$item=array();
foreach($catagories as $cat){
array_push($cats,$cat['name'])
}
file_put_contents('category.json',json_encode($cats));
file_put_contents('items.json',json_encode($item));
Your variable $item is never used, so it won't print anything on the file. You need to use the $items variable
Try
file_put_contents('items.json',json_encode($items));
I think that it is because your item array is empty
$catagories=Catagory::where('status',1)->get(['name'])->toArray();
$items=Item::where('status',1)->get()->toArray();
$cats=array();
$item=array();
foreach($catagories as $cat){
array_push($cats,$cat['name'])
}
file_put_contents('category.json',json_encode($cats));
file_put_contents('items.json',json_encode($item));
You are using $item array on last line which is empty, coz you didn't fill it from $items array
Related
I am looking at parsing some data from JSON and or XML into a table.
I am looking for someone to help me with the basics of this. I need to parse multiple items form the JSON or XML into the table. Below I give my JSON example:
{"appartments":[{"aptnum":"199","design":"open","sqft":"1200","extras":"covered parking","pool":"yes","moveinDate":"2019-01-01 13:12:01","link":"https:\/\/www.demoapts.com\/demo\/199"},{"aptnum":"223","design":"Built Already","sqft":"1800","extras":"covered parking","pool":"yes","moveinDate":"2018-05-09 00:12:01","link":"https:\/\/www.demoapts.com\/demo\/223"}]
What I need help with is parsing this data to a html/Wordpress table.
I also am using a special type of button but I think I have that figured out if I can learn how to parse the data correctly.
I am hoping some of you can help me and point me in the right direction. I have searched on Google and I have only found examples of parsing one item from the JSON.
Here is an example on how you can parse this JSON structure into a table
<?php
$data = json_decode('{"appartments":[{"aptnum":"199","design":"open","sqft":"1200","extras":"covered parking","pool":"yes","moveinDate":"2019-01-01 13:12:01","link":"https:\/\/www.demoapts.com\/demo\/199"},{"aptnum":"223","design":"Built Already","sqft":"1800","extras":"covered parking","pool":"yes","moveinDate":"2018-05-09 00:12:01","link":"https:\/\/www.demoapts.com\/demo\/223"}]}');
// Convert JSON string into a PHP object.
$appartments = $data->appartments;
echo('<table>');
if(!empty($appartments)){
echo('<thead><tr>');
// Using the first object to print column names.
foreach($appartments[0] as $key => $value){
echo('<th>' . $key . '</th>');
}
echo('</tr></thead>');
echo('<tbody>');
// Iterate through all appartments and print them as table cells.
foreach($appartments as $appartment){
echo('<tr>');
foreach($appartment as $key => $value){
echo('<td>' . $value . '</td>');
}
echo('</tr>');
}
echo('</tbody></table>');
}
?>
I have a JSON string strcutred like so:
[{"ip":"", "comment":""}, {"ip":"", "comment":""}]
I'm trying to figure out how to remove one of these objects by identification from the IP and/or comment keys.
The closest i've got so far is this:
my $jsn = decode_json('[{"ip":"1.2.3.4", "comment":"one"}, {"ip":"10.10.10.10","comment":"two"}]');
foreach(#{$jsn}){
if($_->{ip} eq '1.2.3.4'){
print "Found!";
splice #{$jsn}, $_, 1;
}
}
I know splice doesn't work in this example. If i could get the index of the object (ideally without a counter), i think i could then remove the correct object.
grep is your friend here. It creates a new list of elements in an existing list that match an expression.
my #filtered = grep { $_->{ip} ne '1.2.3.4' } #$jsn;
I have a chunk of json that has the following format:
{"page":{"size":7,"number":1,"totalPages":1,"totalElements":7,"resultSetId":null,"duration":0},"content":[{"id":"787edc99-e94f-4132-b596-d04fc56596f9","name":"Verification","attributes":{"ruleExecutionClass":"VerificationRule"},"userTags":[],"links":[{"rel":"self","href":"/endpoint/787edc99-e94f-4132-b596-d04fc56596f9","id":"787edc99-e94f-...
Basically the size attribute (in this case) tells me that there are 7 parts to the content section. How do I convert this chunk of json to an array in Perl, and can I do it using the size attribute? Or is there a simpler way like just using decode_json()?
Here is what I have so far:
my $resources = get_that_json_chunk(); # function returns exactly the json you see, except all 7 resources in the content section
my #decoded_json = #$resources;
foreach my $resource (#decoded_json) {
I've also tried something like this:
my $deserialize = from_json( $resources );
my #decoded_json = (#{$deserialize});
I want to iterate over the array and handle the data. I've tried a few different ways because I read a little about array refs, but I keep getting "Not an ARRAY reference" errors and "Can't use string ("{"page":{"size":7,"number":1,"to"...) as an ARRAY ref while "strict refs" in use"
Thank you to Matt Jacob:
my $deserialized = decode_json($resources);
print "$_->{id}\n" for #{$deserialized->{content}};
I have a classic JSON problem, and i know that many post are asking about that...
But i doubt that the JSON i try to grab has a correct structure.
The files Begin like that :
[{
"time":"0-12h",
"articles":[
{
"id":1,
"domain_id":22,
"title":"Hi Guys"
}
{
"id":2,
"domain_id":17,
"title":"Hi everyone"
}
]
}]
I have try a lot of combinaison to echo the title :
$data = json_decode($json, true);
echo $data->articles;
Or
echo $data->articles->title;
Or
echo $data->articles[0]->title;
Nothing works... :(
Can you help me ?
Thanks !
The second argument true to json_decode() means it should create associative arrays rather than objects for {} in the JSON. So in addition to dealing with the indexed arrays as Explosion Pills points out, you also need to use array syntax to access the keyed elements:
$data[0]['articles'][0]['title']
If you want to be able to use -> syntax, leave out the second argument or set it to false.
I'm hoping the missing comma in the JSON is an error when transcribing to the question. If not, you also need to fix the code that creates the JSON in the first place.
$data itself is an array. Try
$data[0]->articles[0]->title;
Also the JSON is not valid (missing a comma before the second articles array element).
there is a comma , missing
}
,
{
json_decode with the second parameter true returns an array
print_r($data['articles']);
echo $data['articles'] would output Array
I am trying to output some data from Perl to JSON. I can do a simple output, but would like to structure it better.
I have an array with an id, a start time and an end time. This is the code I am using to output:
print header('application/json');
my $json->{$entry} = \#array;
my $json_text = to_json($json);
print $json_text;
Which returns:
{"Season":[["1","1330065300","1344038401"],["7","1298505601","1312416001"]]}
But I would like to output something more like:
{"Season":0[{"id":1,"DateStart":1330065300,"DateEnd":1344038401},{"id":7,"DateStart":1298505601,"DateEnd":1312416001}]}
Can anyone help on how to better structure my output?
---UPDATE------
Thanks Michael. I have tried to implement your example.
This is the code at the moment:
foreach my $key (keys %$seasons)
{
$seasons->{$key} =
[
map
{
{ id=>$_[0], DateStart=>$_[1], DateEnd=>$_[2] }
} #{$seasons->{$key}}
];
}
But it returns the error (referring to the foreach line):
Not a HASH reference at line 148
$seasons is an arrayref return from a SQL fetchall_arrayref
Any clues?
You basically want to convert an array of arrays to an array of hashes, and you can do this using map. Assuming $data is your structure, this should do it:
for my $key (keys %$data) {
$data->{$key} = [
map {
{ id => $_->[0], DateStart => $_->[1], DateEnd => $_->[2] }
} #{$data->{$key}}
];
}
If you want to output an array of objects with key/value pairs instead of an array of arrays, then put appropriate data into to_json in the first place.
i.e. an array of hashrefs and not an array of arrayrefs.
You can use map to transform the data.
Whenever you're trying something like this, always check CPAN to see if someone has done it before and not try to reinvent the wheel. I found a module called JSON that seems to do exactly what you want.
There's an example on that page that does exactly what you want. Here's a quick paraphrase:
use JSON; # imports encode_json, decode_json, to_json and from_json.
# simple and fast interfaces (expect/generate UTF-8)
my $utf8_encoded_json_text = encode_json \#array;
Can't get easier than that. The best part is that this will work no matter how complex your array structure gets.