Having trouble to decode json string - json

I have an json string i want to parse to small array of objects, i am using decoder for that but it wont help, why is this happining?
I have defined the variable as $cleanforcharacters
$cleanforcharacters = preg_replace('/["{mtwrdayfsasusseto}"]_/', '', $found['newdiscounthours']);
this is my output
discount_org: "{"day":"8:00","time":"12:00","discount":"10","day":"8:00","time":"12:00","discount":"10"}"
this is desired output (array of objects)
discount_org: [
{
day: 0,
time: 8,
discount: 10
},
{
day: 0,
time: 14,
discount: 10
},
this is how i tried
$arrayOfEmails = json_decode($cleanforcharacters);
and this is what i am getting now
discount_org: {
day: "20",
time: "12:00",
discount: "20"
}
the rest is not coming out either

This is because you have declared that as an object and the keys are overriding the values rather than being set as new values:-
You have given:-
discount_org: "{"day":"8:00","time":"12:00","discount":"10","day":"8:00","time":"12:00","discount":"10"}"
It should be:-
discount_org: "[{"day":"8:00","time":"12:00","discount":"10"},{"day":"8:00","time":"12:00","discount":"10"}]"
Then use:-
$arrayOfEmails = json_decode($cleanforcharacters,true);
This would give you correct result.

Related

How to access data object from a nested array

I am using ObservableHQ and vega lite API to do data visualizations and have faced a problem I can't figure out.
The problem is that, I would like to access data object from the following data structure,
Array
Array
Array
Item
Item
Array
As you can see in my bad drawing, I have a multidimensional array and would like to access a specific array from the main array. How can I do that using Vegalite API?
vl.markCircle({
thickness: 4,
bandSize: 2
})
.data(diff[0])
.encode(
vl.x().fieldQ("mins").scale({ domain: [-60, 60] }),
vl.color().fieldN('type').scale({ range: ['#636363', '#f03b20'] }),
)
.config({bandSize: 10})
.width(600)
.height(40)
.render()
Thank you,
Based on your comments, I’m assuming that you’re trying to automatically chart all of the nested arrays (separately), not just one of them. And based on your chart code, I’m assuming that your data looks sorta like this:
const diff = [
[
{ mins: 38, type: "Type B" },
{ mins: 30, type: "Type B" },
{ mins: 28, type: "Type A" },
…
],
[
{ mins: 20, type: "Type B" },
{ mins: 17, type: "Type A" },
{ mins: 19, type: "Type A" },
…
],
…
];
First, flatten all the arrays into one big array, and record which array each came from with a new array property on the item object, with flatMap. If each child array represents, say, a different city, or a different year, or a different person collecting the data, you could replace array: i with something more meaningful about the data.
const flat = diff.flatMap((arr, i) => arr.map((d) => ({ ...d, array: i })));
Then use Vega-Lite’s “faceting” (documentation, Observable tutorial and examples) to make split the chart into sections, one for each value of array: i, with shared scales. This just adds one line to your example:
vl
.markCircle({
thickness: 4,
bandSize: 2
})
.data(flat)
.encode(
vl.row().fieldN("array"), // this line is new
vl
.x()
.fieldQ("mins")
.scale({ domain: [-60, 60] }),
vl
.color()
.fieldN("type")
.scale({ range: ["#636363", "#f03b20"] })
)
.config({ bandSize: 10 })
.width(600)
.height(40)
.render()
Here’s an Observable notebook with examples of this working. As I show there at the bottom, you can also map over your array to make a totally separate chart for each nested array.

Extracting one specific line from parsed JSON string

Trying to pull first value from a parsed JSON string using the JsonConverter library.
What I currently have is:
result = objHTTP.responseText
Set parsedResult = JsonConverter.ParseJson(result)
i = 3
For Each Item In parsedResult("From")
wsSheet0.Cells(i, 12) = parsedResult("From")(Item)("Price")
i = i + 1
Next
With parsedResult("From")
wsSheet0.Cells(11, 12) = parsedResult("From")("Chocolate")("Price")("AsAtDate")
End With
The last line of this gets a type mismatch error, so I'm still trying to figure out how to just pull that one line item.
For the sake of clarity, the parsed JSON string looks like:
{
"From":{
"Chocolate":{
"Price":1.0,
"AsAtDate":"2018-05-04T00:00:00"
},
"Lime":{
"Price":1.35415115,
"AsAtDate":"2018-05-04T00:00:00"
},
"Strawberry":{
"Price":1.19517151,
"AsAtDate":"2018-05-04T00:00:00"
},
"Vanilla":{
"Price":0.77522986,
"AsAtDate":"2018-05-04T00:00:00"
},
"Blueberry":{
"Price":1.00084071,
"AsAtDate":"2018-05-04T00:00:00"
},
"Lemon":{
"Price":0.75030012,
"AsAtDate":"2018-05-04T00:00:00"
}
},
"To":"Chocolate",
"RequestedDate":"2018-05-22T08:26:16"
}
Use
parsedResult("From")("Chocolate")("AsAtDate")
Or more generally to get all:
parsedResult("From")(item)("AsAtDate")

How to define a function that adds the values in HashMaps in Python?

The question is : create a function which will calculate the total stock worth in the cafe. You will need to remember to loop through the appropriate maps and lists to do this.
What I have so far :
menu = ("Coffee", "Tea", "Cake", "Cookies")
stock = {
"Coffee" : 10,
"Tea" : 17,
"Cake" : 15,
"Cookies" : 5,
}
price = {
"Coffee" : 'R 12',
"Tea" : 'R 11',
"Cake" : 'R 20',
"Cookies" : 'R 8',
}
def totalstock(stock):
Now I'm stuck, I know there should be a loop and a sum function, but I don't know how to convert the strings to ints so I can add them?
In this case your price dictionary doesn't just have numbers so you'll have to separate the R from the number. Example:
coffee_price = int(price['Coffee'].split(' ')[1])
To explain, take the string at price['Coffee'] and split it, giving a list with 2 values. Return the second value to the int() function to be converted to an integer and stored in coffee_price.

How to get data in specific format using scala?

I have a raw json in following format-
"luns": [
{
"numReadBlocks": 15444876,
"numWriteBlocks": 13530714,
"blockSizeInBytes": 512,
"writeIops": 495344,
"readIops": 312702,
"serialNumber": "aaaaaaa",
"uuid": "id",
"shareState": "none",
"usedBytes": 6721716224,
"totalSizeBytes": 16106127360,
"path": "/vol/lun_23052014_025830_vol/lun_23052014_025830"
},
{
"numReadBlocks": 15444876,
"numWriteBlocks": 13530714,
"blockSizeInBytes": 512,
"writeIops": 495344,
"readIops": 312702,
"serialNumber": "aaaaaaa",
"uuid": "id",
"shareState": "none",
"usedBytes": 6721716224,
"totalSizeBytes": 16106127360,
"path": "/vol/lun_23052014_025830_vol/lun_23052014_025830"
}]
The luns may contains list.
I want to process above json and form output as following-
"topStorageLuns": [
{
"name": "Free (in GB)",
"data": [7.79,7.79]
},
{
"name": "Used (in GB)",
"data": [7.21,7.21]
}]
I tried following in order to get output-
val storageLuns = myRawJson
val topStorageLuns = storageLuns.map { storageLun =>
val totalLunsSizeOnStorageDevice = storageLun.luns.foldLeft(0.0) {
case (totalBytesOnDevice, lun) =>
totalBytesOnDevice + lun.usedBytes.getOrElse(0.0).toString.toLong
}
val totalAvailableLunsOnStorageDevice = storageLun.luns.foldLeft(0.0) {
case (totalBytesOnDevice, lun) =>
totalBytesOnDevice + lun.usedBytes.getOrElse(0.0).toString.toLong
}
Json.obj("name" -> storageLun.hostId, "data" -> "%.2f".format(totalLunsSizeOnStorageDevice / (1024 * 1024 * 1024)).toDouble)
}
Can anybody help me to get desired output please???
The key lesson I want to impart is that your algorithm should reflect the shape of the output you want. Work backward from the result you want to build the algorithm.
It looks to me like you want to create an array of length 2, where each entry has a corresponding algorithm (spaced used, space free). Within each of these elements, you want a nested array with an element for each item in your input array, calculated using the algorithm from the outer array. Here's how I would approach the problem:
1) Define your algorithms
val dfAlgorithm: (Seq[(String, JsValue)] => Double) = _.foldLeft(0.0) { (acc, item) =>
/* whatever logic you need to do */
}
val duAlgorithm: (Seq[(String, JsValue)] => Double) = _.foldLeft(0.0) { (acc, item) =>
/* whatever logic you need to do */
}
2) Create a data structure to map over to build your final output
val stats = Seq("Free (in GB)" -> dfAlgorithm, "Used (in GB)" -> duAlgorithm)
3) Map over your input data within your mapping over your algorithms (the logic here reflects the shape of the result you want)
stats.map { case (name, algorithm) =>
Json.obj("name" -> name, "data" -> storageLuns.map { storageLun => algorithm(storageLun) }
}
This isn't going to be a turnkey solution, since I don't know how your free/used algorithms are supposed to work, but this overall scheme should get you there.

Importing a csv into d3; can't convert strings to numbers

I have a csv file with data as follows:
Time, Conditions, Temperature, Humidity, WindDir, WindDeg, U1, Pressure, U2, U3, U4, U4, UV, U5, MoonPercent, SunriseHr, SunriseMin, SunsetHr
"2014/06/19 19:00:00", "Clear", 16.8, "87%", "North", 355, 8.0, "1010", "11", 15, "NA", "1.2", " 0", "11", "47", "5", "03" "22", "07"
"2014/06/19 19:31:01", "Mostly Cloudy", 17.2, "86%", "NNE", 26, 12.9, "1010", "11", 15, "NA", "0.7", " 0", "11", "47", "5", "03" "22", "07"
"2014/06/19 19:40:00", "Mostly Cloudy", 17.4, "85%", "ENE", 68, 6.4, "1010", "11", 15, "NA", "0.7", " 0", "11", "47", "5", "03" "22", "07"
I want to import it and have array contain the numbers as numbers, not as strings as it does at first:
Object { Time="2014/06/19 19:00:00", Conditions=" "Clear"", Temperature=" 16.8", more...}
The problem is, no matter what I try I've not been able to turn the numbers into actual numbers, just NaN. Here's my import code:
d3.csv("weatherLog.csv", function(error, csv) {
if (error) return console.warn(error);
csv.forEach(function(d){ (d['Temperature'] = +d['Temperature']); });
console.log(csv);
I tried d.Temperature instead, I tried parseInt(d.['Temperature']) instead, but nothing works out, and of course d3 can't use a string (or a NaN) as data so I need to convert this first somehow. I tried manually removing the space from the CSV file (so the imported string was "16.8" rather than " 16.8") but that didn't help either...
You should use an accessor function to convert the strings to dates and numbers. The way to do that is to use the .row() method, which iterates over the rows of your csv, and for each row, lets you provide an output object that will be used to represent that row, based on the given data.
The parameter given to the accessor, d, represents a single row, or datum. Within the accessor function, d has properties corresponding to the names of your data columns, such as Time, Conditions, Temperature, etc... You can manipulate these values before returning your output object, so in the case of temperature, you could assign the temperature property of your output object to be +d.Temperature, which converts it to a number.
By convention, property names are camel cased in JavaScript, so the object you return from the accessor should use camel cased keys.
Now when your callback runs, your variable csv contains an array of objects, each of which has properties such as time, conditions, temperature, etc... and the values for temperature have been converted to numbers.
Here is an example:
d3.csv('weatherLog.csv')
.row(function(d) {
// for each row of the data, create an object with these properties...
return {
time: d3.time.format('%Y/%m/%d %H:%M:%S').parse(d.Time),
conditions: d.Conditions,
temperature: +d.Temperature,
humidity: d.Humidity,
windDir: d.WindDir,
windDeg: +d.WindDeg,
pressure: +d.Pressure
};
})
.get(function(error, csv) {
if (!error) {
// lets say you want to log all the temperatures to the console
csv.forEach(function(d,i) {
var theTime = d3.time.format('%I:%M %p')(d.time);
console.log('The temperature at', theTime, 'was', d.temperature, 'degrees.');
});
} else {
// handle error
}
});
This will output the following to console:
The temperature at 7:00 PM was 16.8 degrees.
The temperature at 7:31 PM was 17.2 degrees.
The temperature at 7:40 PM was 17.4 degrees.
This worked for me.
d3.csv("weatherLog.csv", function(d) {
return {
temperature: +d.Temperature;
}
}, function(error, csv) {
if (error) return console.warn(error);
console.log(csv);
});