I've been able to parse some JSON succesfully up to a point but cannot access a specific object:
My overall code:
$myFile = Get-Content -Raw -Path UKStore.json | ConvertFrom-Json
$counter = 0
foreach ($link in $myFile.links)
{
Write-Host $link.id "and" $link.name
Write-Host $link.default_sku
$counter+=1
}
Write-Host $counter
Read-Host -Prompt "Press Enter to exit"
Now, what I get for each iteration is something like this below. So, line 1 is great and is outputting what I need but line 2 needs to be processed further:
EP9000-NPEE00001_00-GCRASHBAND000001 and Crash Bandicoot®
#{amortizeFlag=False; bundleExclusiveFlag=False; chargeImmediatelyFlag=False; charge_type_id=0; credit_card_required_flag=0; defaultSku=True; display_price=£3.99; eligibilities=System.Object[]; entitlements=System.Object[]; id=EP9000-NPEE00001_00-GCRASHBAND000001-EE03; is_original=False; name=Full Game; platforms=System.Object[]; price=399; rewards=System.Object[]; seasonPassExclusiveFlag=False; skuAvailabilityOverrideFlag=False; sku_type=0; type=standard}
I simply cannot, no matter what notation I try get access to the properties in "$link.default_sku" I'm clearly not connecting something right in my brain but I feel that:
$link.default_sku.display_price
Should give me the value £3.99 from the above object but instead I get nothing returned at all. Any help to get through this mental blockage would be great.
Went a level higher for Format-Custom
$link | Format-Custom
Output:
class PSCustomObject
{
bucket = games
container_type = product
content_type = 1
default_sku = #{amortizeFlag=False; bundleExclusiveFlag=False; chargeImmediatelyFlag=False; charge_type_id=0;
credit_card_required_flag=0; defaultSku=True; display_price=£24.99; eligibilities=System.Object[];
entitlements=System.Object[]; id=EP2595-CUSA07370_00-0001000100010001-E001; is_original=False; name=Full Game;
platforms=System.Object[]; price=2499; rewards=System.Object[]; seasonPassExclusiveFlag=False;
skuAvailabilityOverrideFlag=False; sku_type=0; type=standard}
gameContentTypesList =
game_contentType = Full Game
id = EP2595-CUSA07370_00-0001000100010001
images =
name = Past Cure™
playable_platform = PS4™
provider_name = Phantom 8 Studio UG
release_date =
class DateTime
{
Date =
class DateTime
{
Date =
class DateTime
{
Date =
class DateTime
{
Date =
class DateTime
{
Date = 23/02/2018 00:00:00
Day = 23
DayOfWeek = Friday
DayOfYear = 54
Hour = 0
Kind = Utc
Millisecond = 0
Minute = 0
Month = 2
Second = 0
Ticks = 636549408000000000
TimeOfDay = 00:00:00
Year = 2018
DateTime = 23 February 2018 00:00:00
}
Day = 23
DayOfWeek = Friday
DayOfYear = 54
Hour = 0
Kind = Utc
Millisecond = 0
Minute = 0
Month = 2
Second = 0
Ticks = 636549408000000000
TimeOfDay =
class TimeSpan
{
Ticks = 0
Days = 0
Hours = 0
Milliseconds = 0
Minutes = 0
Seconds = 0
TotalDays = 0
TotalHours = 0
TotalMilliseconds = 0
TotalMinutes = 0
TotalSeconds = 0
}
Year = 2018
DateTime = 23 February 2018 00:00:00
}
Day = 23
DayOfWeek = Friday
DayOfYear = 54
Hour = 0
Kind = Utc
Millisecond = 0
Minute = 0
Month = 2
Second = 0
Ticks = 636549408000000000
TimeOfDay =
class TimeSpan
{
Ticks = 0
Days = 0
Hours = 0
Milliseconds = 0
Minutes = 0
Seconds = 0
TotalDays = 0
TotalHours = 0
TotalMilliseconds = 0
TotalMinutes = 0
TotalSeconds = 0
}
Year = 2018
DateTime = 23 February 2018 00:00:00
}
Day = 23
DayOfWeek = Friday
DayOfYear = 54
Hour = 0
Kind = Utc
Millisecond = 0
Minute = 0
Month = 2
Second = 0
Ticks = 636549408000000000
TimeOfDay =
class TimeSpan
{
Ticks = 0
Days = 0
Hours = 0
Milliseconds = 0
Minutes = 0
Seconds = 0
TotalDays = 0
TotalHours = 0
TotalMilliseconds = 0
TotalMinutes = 0
TotalSeconds = 0
}
Year = 2018
DateTime = 23 February 2018 00:00:00
}
Day = 23
DayOfWeek = Friday
DayOfYear = 54
Hour = 0
Kind = Utc
Millisecond = 0
Minute = 0
Month = 2
Second = 0
Ticks = 636549408000000000
TimeOfDay =
class TimeSpan
{
Ticks = 0
Days = 0
Hours = 0
Milliseconds = 0
Minutes = 0
Seconds = 0
TotalDays = 0
TotalHours = 0
TotalMilliseconds = 0
TotalMinutes = 0
TotalSeconds = 0
}
Year = 2018
DateTime = 23 February 2018 00:00:00
}
restricted = False
revision = 15
short_name = Past Cure™
timestamp = 1648353047000
top_category = downloadable_game
url = https://store.playstation.com/store/api/chihiro/00_09_000/container/GB/en/999/EP2595-CUSA07370_00-0001000100010
001/1648353047
}
$link.default_sku contains a string, not a nested object, and that's why $link.default_sku.display_price doesn't work.
That string happens to be the stringification of a nested [pscsutomobject], such as you would get with string interpolation (e.g., "$([pscustomobject] #{ foo=1; bar =2 })" or - most likely in this case - when the default recursion depth of 2 is exceeded during creation of JSON text using ConvertTo-Json, a common and regrettable pitfall - see this post.
You have two options:
Fix the problem at the source, by passing a -Depth argument that is sufficiently high to ConvertTo-Json to prevent truncation when the UKStore.json file is created.
If that is not an option, you'll have to do text parsing to extract the value of interest from the string. Note, however, that this isn't generally robust, because the stringification format of [pscustomobject]s is meant for the human observer, not for programmatic processing. Notably, quotation marks around string values with spaces are lost:
# -> '£24.99'
$link.default_sku -replace '(?s).+\bdisplay_price=([^;]+).+', '$1'
Related
def PER_Calc(PERatio,PECom):
print("I am here")
print(PERatio,"inside")
if PERatio >= 0 and PERatio <= 18:
PECom = 10
PERatio = PERatio + 2
return PECom
PECom = 0
PERatio = 18
PER_Calc(PERatio,PECom)
print(PERatio)
print(PECom)
RESULTS ARE
I am here
18 inside
18
0
SHOULD BE
I am here
18 inside
20
10
Add numbers of hours to a timestamp and make sure that the output is within working hours.
For example:
Open Time -> 9:00 AM
Close Time -> 6:00 PM
First Date -> 12/1/2020 12:00 PM
Add Time -> 7 hours
Result -> 13/1/2020 10:00 AM
I am trying to achieve this using GAS ES5/ES6
Already tried a formula which is very close to this logic:
Cell A7 = First Date
Cell G5 = Add Time
Cell B1 = 9/24-18/24
Sheet2!A:A = List of Holidays to Skip
0000011 = Skips Saturday and Sunday
=if(A7,if(and(hour(A7+G$5)>9,(hour(A7+G$5)<18)),A7+G$5,workday.intl(int(A7+G$5+$B$1),1,"0000011",Sheet2!A:A)+hour(A7+G$5+$B$1)/24),"")
I think you are looking for this:
function myFunction() {
var open_h = 9 // 24h
var close_h = 18 //24h
var add_h = 7 // number of hours
var d = new Date();
d.setDate(d.getDate() + (1 + 7 - d.getDay()) % 7);
next_Monday = d.getDate()
var first_date = new Date() ;
var end_date = new Date();
end_date.setTime(end_date.getTime() + (add_h*60*60*1000))
if (end_date.getDate()>first_date.getDate()){
end_date.setDate((new Date()).getDate());
end_date.setHours(23, 0 , 0);
}
if (end_date.getHours()>=close_h){
if (end_date.getDay() == 5 || end_date.getDay() == 6 || end_date.getDay() == 0 ) {end_date.setDate(next_Monday) }
else {end_date.setDate(end_date.getDate() + 1)} // tomorrow
var end_time = end_date.getHours()-close_h + open_h
end_date.setHours(end_time, 0, 0);
}
Logger.log(end_date)
} // end function
end_date will give you the desired result.
Edit: it also takes weekends into consideration.
I have to display how many votes were issued on each day (from the first vote, until the last vote) users voted for poll 2.
My current query works fine; but I'm having trouble when a specific day doesn't have any votes in it. For example, for poll 2, this should be the result:
May, 11 2017 = 1
May, 12 2017 = 0
May, 13 2017 = 0
May, 14 2017 = 0
May, 15 2017 = 0
May, 16 2017 = 0
May, 17 2017 = 1
May, 18 2017 = 0
May, 19 2017 = 0
May, 20 2017 = 2
...but instead I'm getting this:
May, 11 2017 = 1
May, 17 2017 = 1
May, 20 2017 = 2
So, what I need is that all days that contain no records (between the first and last vote) also appear in the results. This is my current query:
SELECT DATE(poll_vote.date_insert) AS date_insert,
COUNT(poll_vote.id_vote) AS q
FROM poll_vote WHERE poll_vote.id_poll = 2
GROUP BY DATE(date_insert) ORDER BY date_insert
Here's the SQL Fiddle with the example data. Thanks!
As suggested by #Strawberry, I ended up writing a solution in php instead of mysql. For anyone interested, here's the code.
This solution only returns 0 in 1 day in between blank dates because that's what I needed. Example:
May, 11 2017 = 1
May, 16 2017 = 0
May, 17 2017 = 1
May, 19 2017 = 0
May, 20 2017 = 2
That allows me to display a trending line chart just like this one:
$sql = 'SELECT DATE(poll_vote.date_insert) AS date_insert, COUNT(poll_vote.id_vote) AS q FROM poll_vote WHERE poll_vote.id_poll = :id_poll GROUP BY DATE(date_insert) ORDER BY date_insert';
$stmt = cnn()->prepare($sql);
if($id_poll) $stmt->bindValue(':id_poll', $id_poll, PDO::PARAM_INT);
$stmt->execute();
$data = $stmt->fetchAll();
# insert blank dates between existing dates
$hotness = array();
foreach($data as $item) {
if(!$temp) {
$temp = $item['date_insert'];
} else {
$date_past = new DateTime($temp);
$date_now = new DateTime($item['date_insert']);
$diff = $date_now->diff($date_past)->format("%a");
if($diff > 1) {
$date_new = new DateTime($item['date_insert']);
$date_new->modify('-1 day');
$hotness[] = array(
'date_insert' => $date_new->format('Y-m-d'),
'q' => 0
);
}
}
$hotness[] = array(
'date_insert' => $item['date_insert'],
'q' => $item['q']
);
}
# final result
print_r($hotness);
Ι have a table in MySQL with
date starttime endtime
11/2/2014 10:00:00 10:45:00
11/2/2014 10:45:00 11:15:00
11/2/2014 11:45:00 12:15:00
11/2/2014 12:15:00 13:30:00
I need the sql query to give back to me the time that I can set a new meeting for 30 min
$array_time = array();
$query = "SELECT starttime, endtime FROM table";
$result = $mysqli->query($query);
//fetch result
while ($array_time[] = $result->fetch_assoc()) {}
/*
$array_time = Array (
...
1 => array('starttime' => 10:45:00, 'endtime' => 11:15:00)
2 => array('starttime' => 11:45:00, 'endtime' => 12:15:00)
...
)
*/
//array of free time for your meeting
$free_time = array();
foreach($array_time as $i => $row){
if($i > 0) {
//if this is not the first time row
//get this row starttime
$this_starttime = strtotime($row['starttime']);
//and the last endtime
$prev_endtime = strtotime($array_time[$i-1]['endtime']);
//get the difference
$diff = $this_starttime - $prev_endtime;
//if difference is more or equal than 30 minutes
if($diff >= strtotime('30 minutes')) {
$free_time[] = array('starttime' => $row['starttime'], $array_time[$i-1]['endtime']);
}
}
}
I think you can't do this in MySQL query, so PHP could help you.
Hope it works, I have not tested it out.
But try to save your data by other way, this is not so effective, as you can see.
I am developing a hotel room reservation system, There having only 5 rooms. I want to get the date periods if 5 or more bookings are already done.
Example:
+-------------------------------------------------------------+
|Booking_from_date | Booking_to_date | Number_of_booking_rooms|
+------------------+-----------------+------------------------+
| 2013-01-01 | 2013-01-10 | 3 |
+------------------+-----------------+------------------------+
| 2013-01-06 | 2013-01-15 | 2 |
---------------------------------------------------------------
(now there are total 5 room booked between 2013-01-06 to 2013-01-10, so i want to get this date period).
I tried using MySql, but not achieved yet. Is it possible to create a query like this?
There may a different simpler way, but what i can think of is to split the days and group it yo get sum.
select date_add(a.booking_from_date, interval col1 day),
sum(Number_of_booking_rooms) from
(select * from table1)a,
(select 0 col1 union all
select 1 col1 union all
select 2 union all
select 3 union all
select 4 union all
select 5 union all
select 6 union all
select 7 union all
select 8 union all
select 9) b
where date_add(a.booking_from_date, interval col1 day) <= a.booking_to_date
group by date_add(a.booking_from_date, interval col1 day)
having sum(Number_of_booking_rooms) >= 5
http://sqlfiddle.com/#!2/87813/15
This is the result i got.
DATE SUM
January, 06 2013 00:00:00+0000 5
January, 07 2013 00:00:00+0000 5
January, 08 2013 00:00:00+0000 5
January, 09 2013 00:00:00+0000 5
January, 10 2013 00:00:00+0000 5
I guess this is not possible from just MySql query.But I have a solution by using loop. Please check this code, you will get the output which you want.
/* all active booking from mysql table. */
$this -> data['booked_dates'] = $this -> admin_model -> get_booked_dates_from();//(just a function to get all dates from table)
$array_index = 0;
$not_available_date_range = array();
//declaration
$not_available_date = array();
foreach ($this -> data['booked_dates'] as $key => $booked_date)// loop for each booking dates(each table row).
{
//flag to know package is to be blocked or not...
$block_status = 0;
$check_in_min_date = 0;
$check_out_max_date = 0;
$strDateFrom = $booked_date -> check_in_date;
$strDateTo = $booked_date -> check_out_date;
// Takes two dates, formatted in YYYY-MM-DD.
// Inclusive array of the dates between the from and to dates.
$aryRange = array();
$iDateFrom = strtotime($strDateFrom);
$iDateTo = strtotime($strDateTo);
if ($iDateTo >= $iDateFrom)//just a validation
{
array_push($aryRange, date('Y-m-d', $iDateFrom));
// first entry
$date_gap = 0;
while ($iDateFrom <= $iDateTo)//select each date...between check-in date and check-out date. one by one
{
$date_gap++;
$booking_count = 0;
for ($i = $key; $i <= (count($this -> data['booked_dates']) - 1); $i++)// loop for each booking. // loop have to reduce size. by using good logic..:)
{
$strDateFrom2 = strtotime($this -> data['booked_dates'][$i] -> check_in_date);
$strDateTo2 = strtotime($this -> data['booked_dates'][$i] -> check_out_date);
if (($iDateFrom >= $strDateFrom2) && ($iDateFrom <= $strDateTo2))
{
$booking_count = $booking_count + $this -> data['booked_dates'][$i] -> rooms;
}
}
if ($booking_count >= 5)// compare with maximum available rooms.
{
$block_status = 1;
//room should be blocked.
if ($check_in_min_date == 0)
{
$check_in_min_date = $iDateFrom;
$check_out_max_date = $iDateFrom;
//For if only one day is going to block.
}
else
{
$check_out_max_date = $iDateFrom;
//datefrom is incremented till the maximum booked date.
}
array_push($not_available_date, date('Y-m-d', $iDateFrom));
}
$iDateFrom += 86400;
// add 24 hours
}
}
else
{
echo 'Wrong input!';
}
if ($block_status)//if the room is blocked..
{
$not_available_date_range[$array_index]['check_in_date'] = date('Y-m-d', $check_in_min_date);
$not_available_date_range[$array_index]['check_out_date'] = date('Y-m-d', $check_out_max_date);
$array_index++;
}
}
$this -> data['blocked_dates'] = $not_available_date_range; // Now we have booking period where more than 5 bookings are done.