Array push to multidimensional array for JSON - json

Can someone pls help me on how to array_push to a multidimensional array.
This is my code for pushing.
$arrDataChart3["categories"] = array();
array_push($arrDataChart3["categories"], array(
"category"=>array ()
)
);
while($row = sqlsrv_fetch_array($myAcc2)) {
array_push($arrDataChart3["categories"]["category"], array(
"label" => $row["position"])
);
}
i want to push $row["position"] to "category" from my database.
Here's what the array should contain.
"categories": [
{
"category": [
{
"label": "Q1"
},
{
"label": "Q2"
},
{
"label": "Q3"
},
{
"label": "Q4"
}
]
}
],
Thanks in advance

i used this solved the problem
$arrDataChart3["categories"] = array();
$arr=array ();
while($row = sqlsrv_fetch_array($myAcc2)) {
array_push($arr, array(
"label"=>$row['position']
)
);
}
array_push($arrDataChart3["categories"], array(
"category"=>$arr
)
);

Related

how to create json response status in codeigniter

I made json code using json encode, the results are correct, but I want to add a satatus response to the object. How to ?
this my code
public function get(){
header('Content-Type: application/json');
$db = $this->M_order->db_order();
$response = array();
$data = array();
foreach ($db as $key) {
$data[] = array(
'id' => $key->id_user,
'name' => $key->name,
'destination' =>$key->destination
);
}
$response['data'] = $data;
echo json_encode($response, TRUE);
}
this result my json
{
"data": [
{
"id": "1",
"name": "amar",
"destination": "USA"
}
]
}
here I want to add a status header in object, like the following ...
{
"status": 200,
"error": false,
"data": [
{
"id": "1",
"name": "amar",
"destination": "USA"
},
]
}
how to create ?
As I understand your question,
$response = array();
$data = array();
foreach ($db as $key) {
$data[] = array(
'id' => $key->id_user,
'name' => $key->name,
'destination' =>$key->destination
);
}
$response['status'] = 200;
$response['error'] = false;
$response['data'] = $data;

Perl Create JSON string in a specific format

I have a table with 3 fields that I query and put the values in a JSON. The table has hostname to application name and application id. I currently have a perl script that outputs the following json string.
[
{
"app_id" : "1234",
"app_name" : "Managed File Transfer",
"ci_name" : "hosta7"
},
{
"app_name" : "Patrtol",
"app_id" : "1235",
"ci_name" : "hosta7"
},
{
"app_id" : "1236",
"app_name" : "RELATIONAL DATA WAREHOUSE",
"ci_name" : "hosta7"
},
{
"ci_name" : "hosta7",
"app_id" : "1237",
"app_name" : "Managed File Transfer"
},
{
"app_id" : "1238",
"app_name" : "Initio Application",
"ci_name" : "hosta7"
},
{
"app_id" : "1239",
"app_name" : "Data Warehouse Operations Infrastructure",
"ci_name" : "hosta7"
},
{
"app_id" : "2345",
"app_name" : "Tableou",
"ci_name" : "hostb"
}
]
I want the resulting json string like the following where if the ci_name already exists, I want the new item to be added to the current entry of the host in the JSON string. So essentially, I want this JSON string
{
"hosts" : [{
"hosta" :[
{
"app_id": "1234",
"app_name": "Managed File Transfer"
},
{
"app_id": "1235",
"app_name": "Patrol"
},
{
"app_id": "1236",
"app_name": "RELATIONAL DATA WAREHOUSE"
},
{
"app_id": "1237",
"app_name": "Managed File Transfer"
},
{
"app_id": "1238",
"app_name": "Initio Application"
},
{
"app_id": "1239",
"app_name": "Data Warehouse Operations Infrastructure"
}
],
"hostb" : [
{
"app_id": "2345",
"app_name": "Tableou"
}
]
}]
}
#!/usr/bin/perl
use strict;
use warnings;
use JSON;
my $hosts = [
{
'app_id' => '1234',
'app_name' => 'Managed File Transfer',
'ci_name' => 'hosta7'
},
{
'app_name' => 'Patrtol',
'app_id' => '1235',
'ci_name' => 'hosta7'
},
{
'app_id' => '1236',
'app_name' => 'RELATIONAL DATA WAREHOUSE',
'ci_name' => 'hosta7'
},
{
'ci_name' => 'hosta7',
'app_id' => '1237',
'app_name' => 'Managed File Transfer'
},
{
'app_id' => '1238',
'app_name' => 'Initio Application',
'ci_name' => 'hosta7'
},
{
'app_id' => '1239',
'app_name' => 'Data Warehouse Operations Infrastructure',
'ci_name' => 'hosta7'
},
{
'app_id' => '2345',
'app_name' => 'Tableou',
'ci_name' => 'hostb'
}
];
my $output;
foreach my $row (#$hosts) {
push #$output, $row;
}
my $json = new JSON;
$json->pretty(1);
print $json->encode($output);
You don't want to push directly, you want to push under a key taken from the ci_name, and you only want to copy the app id and name.
for my $element (#$hosts) {
push #{ $output->{ $element->{ci_name} } },
{ map { $_ => $element->{$_} } qw( app_id app_name ) };
}
Probably the code will look like following snippet
#!/usr/bin/perl
use strict;
use warnings;
use JSON;
use Data::Dumper;
my $debug = 0;
my %data;
while( <DATA> ) {
chomp;
next if /app_id/;
my ($app_id,$ci_name,$app_name) = split /,/;
push #{$data{hosts}{$ci_name}}, {app_id => $app_id, app_name => $app_name };
}
print Dumper(\%data) if $debug;
my $json = encode_json \%data;
print $json;
__DATA__
app_id,ci_name,app_name
1234,hosta7,Managed File Transfer
1235,hosta7,Patrtol
1236,hosta7,RELATIONAL DATA WAREHOUSE
1237,hosta7,Managed File Transfer
1238,hosta7,Initio Application
1239,hosta7,Data Warehouse Operations Infrastructure
2345,hostb,Tableou

file_get_contents parse json insert database

Hi I encountered a problem. I will record the data I received from the database.
JSON=>
{
"success": true,
"timestamp": 1565251506,
"base": "EUR",
"date": "2019-08-08",
"rates": {
"AED": 4.119657,
"AFN": 87.689574,
"ALL": 121.192477,
"AMD": 533.113395,
"ANG": 1.998509,
"AOA": 398.760307,
"ARS": 51.036305,
"AUD": 1.654423
}
}
After Json decode
array:5 [
"success" => true
"timestamp" => 1565205306
"base" => "EUR"
"date" => "2019-08-07"
"rates" => array:168 [
"AED" => 4.118588
"AFN" => 87.74397
"ALL" => 121.002609
"AMD" => 534.279745
"ANG" => 2.001014
]
]
I want this=> But How do I get quote and rate?
$response = file_get_contents("rate.json");
$datas = json_decode($response, true);
foreach ($datas as $data) {
$rates = new Rate();
$rates->base = $datas['base'];
$rates->quote = 'AED';
$rates->rate = '4.119657';
$rates->save();
}
You're looping over the wrong thing here, you should be looping over the rates and saving the corresponding key and value:
$response = file_get_contents("rate.json");
$data = json_decode($response, true);
foreach ($data['rates'] as $quote => $rate) {
$rates = new Rate();
$rates->base = $data['base'];
$rates->quote = $quote;
$rates->rate = $rate;
$rates->save();
}

Google Slides Batch Update Errors - "Invalid JSON payload received. Unknown name" & " Cannot bind query parameter"

I'm trying to write to a slide element.
I keep getting the error responses of "Invalid JSON payload received. Unknown name" and " Cannot bind query parameter. Field"
My request is
{
"requests": [
{
"deleteText": {
"objectId": "g33c4ea3b90_0_9",
"textRange": {
"type": "FROM_START_INDEX",
"startIndex": 0
}
}
},
{
"insertText": {
"objectId": "g33c4ea3b90_0_9",
"text": "$8.23",
"insertionIndex": 0
}
}
]
}
I am posting to: https://slides.googleapis.com/v1/presentations/PRESENTATION_ID:batchUpdate?access_token=ACCESS_TOKEN
I am manually cURLing the request in PHP:
$params = '
{
"requests": [
{
"deleteText": {
"objectId": "'.$page_object_id.'",
"textRange": {
"type": "FROM_START_INDEX",
"startIndex": 0
}
}
},
{
"insertText": {
"objectId": "'.$page_object_id.'",
"text": "$8.23",
"insertionIndex": 0
}
}
]
}
';
$options = array(
CURLOPT_RETURNTRANSFER => true, // return web page
CURLOPT_HEADER => false, // don't return headers
CURLOPT_FOLLOWLOCATION => true, // follow redirects
CURLOPT_MAXREDIRS => 10, // stop after 10 redirects
CURLOPT_ENCODING => "", // handle compressed
CURLOPT_AUTOREFERER => true, // set referrer on redirect
CURLOPT_CONNECTTIMEOUT => 120, // time-out on connect
CURLOPT_TIMEOUT => 120, // time-out on response
CURLOPT_CUSTOMREQUEST => 'POST' ,
CURLOPT_SSL_VERIFYPEER => false,
CURLOPT_SSL_VERIFYHOST => false ,
CURLINFO_HEADER_OUT => true ,
CURLOPT_VERBOSE => true,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $params
);
$ch = curl_init($url);
curl_setopt_array($ch, $options);
$content = curl_exec($ch);
curl_close($ch);
$obj = json_decode($content, true);
print_r( $obj );
When I call it from the API Explorer it works perfectly, but not from my server.
So the problem was the use of double quotes instead of single quotes in the request parameter json string.
So the following works:
{
'requests': [
{
'deleteText': {
'objectId': 'g33c4ea3b90_0_9',
'textRange': {
'type': 'FROM_START_INDEX',
'startIndex': 0
}
}
},
{
'insertText': {
'objectId': 'g33c4ea3b90_0_9',
'text': '$44.23',
'insertionIndex': 0
}
}
]
}
I had been working on this for two days.

Unable to display data from json.net

Can anyone help solve this problem, no matter what i try i cannot display the data on webpage, i can put a breakpoints at JObject o = JObject.Parse(ws); and see the data, but every attempt i have tried results in a different error.I'm trying to do is get the areaName and country.
I have tried the examples from: http://james.newtonking.com/projects/json/help/ and http://forums.asp.net/t/1780822.aspx/1?How+to+traverse+in+json+ with no luck
Any help would be appreciated.
George
My code is below:
string ws = #"{ ""search_api"": { ""result"": [ { ""areaName"": [ {""value"": ""London"" } ], ""country"": [ {""value"": ""United Kingdom"" } ], ""latitude"": ""51.517"", ""longitude"": ""-0.106"", ""population"": ""7421228"", ""region"": [ {""value"": ""City Of London, Greater London"" } ], ""timezone"": [ {""offset"": ""1.0"" } ], ""weatherUrl"": [ {""value"": ""http:\/\/www.worldweatheronline.com\/London-weather\/City-of-London-Greater-London\/GB.aspx"" } ] }, { ""areaName"": [ {""value"": ""London"" } ], ""country"": [ {""value"": ""Canada"" } ], ""latitude"": ""42.983"", ""longitude"": ""-81.250"", ""population"": ""346774"", ""region"": [ {""value"": ""Ontario"" } ], ""timezone"": [ {""offset"": ""-4.0"" } ], ""weatherUrl"": [ {""value"": ""http:\/\/www.worldweatheronline.com\/London-weather\/Ontario\/CA.aspx"" } ] } ] }}";
JObject o = JObject.Parse(ws);
var weatherCity = o["areaName"][0]["value"];
ViewBag.WeatherSearch = weatherCity.ToString();
//var weatherCity = o["search_api"][0]["result"]["areaName"]["value"];
// JArray arr = (JArray)o.SelectToken("search_api");
// JObject cityTown = (JObject)arr[0].SelectToken("result").SelectToken("areaName");
// var weatherCity = cityTown.SelectToken("value");
// IList<string> WeatherCity = o.SelectToken("result").Select(s => (string)s).ToList();
//string WeatherCity = (string)o.SelectToken("result[0].areaName[0].value");
//IList<string> WeatherCities = o["result"].Select(m => (string)m.SelectToken("areaName[0].value")).ToList();
How about something like:
var weatherCity = o["search_api"]["result"][0]["areaName"][0]["value"];
o represents the root, so you can't skip any nodes.