I need to write a new geoJSON feature to a data.json file using php. Right now I'm writing my data to the file like so:
<?php
// Read from json file
$jsondata = json_decode( file_get_contents('data.json') );
// Add the new data
$jsondata []= array(
'measure_location'=> $_POST["measure_location"],
'measure_type'=> $_POST["measure_type"],
'measurement'=> $_POST["measurement"],
'note_text'=> $_POST["note_text"]
);
// encodes the array into a string in JSON format (JSON_PRETTY_PRINT - uses whitespace in json-string, for human readable)
$jsondata = json_encode($jsondata, JSON_PRETTY_PRINT);
// saves the json string in "data.json" (in "dirdata" folder)
// outputs error message if data cannot be saved
if(file_put_contents('data.json', $jsondata));
?>
And this is what the data then looks like in data.json:
{
"measure_location": "52.370611247493486, 4.91587221622467",
"measure_type": "negative",
"measurement": "violence",
"note_text": ""
}
Could I adjust my PHP code to make the data look like so:
{
"type": "Feature",
"geometry": {
"type": "Point",
"coordinates": [
"4.91587221622467",
"52.370611247493486"
]
},
"properties": {
"type": "negative",
"input": "violence",
"note": ""
}
}
Got the answer thanks to charlietfl. Changed the php code to:
<?php
// Read from json file
$jsondata = json_decode( file_get_contents('data.json') );
// Add the new data
$jsondata [] = array(
'type' => 'Feature',
'geometry' => array(
'type' => 'Point',
'coordinates' => $_POST["measure_location"],
),
'properties' => array(
'type' => $_POST["measure_type"],
'input' => $_POST["measurement"],
'note' => $_POST["note_text"],
)
);
// encodes the array into a string in JSON format (JSON_PRETTY_PRINT - uses whitespace in json-string, for human readable)
$jsondata = json_encode($jsondata, JSON_PRETTY_PRINT);
// saves the json string in "data.json" (in "dirdata" folder)
// outputs error message if data cannot be saved
if(file_put_contents('data.json', $jsondata));
?>
I cannot the code that works for you. I have tried many times. It produced a wrong format JSON. The correct code should be,
$jsondata -> features [] = array(
'type' => 'Feature',
'geometry' => array(
'type' => 'Point',
'coordinates' => $_POST["measure_location"],
),
'properties' => array(
'type' => $_POST["measure_type"],
'input' => $_POST["measurement"],
'note' => $_POST["note_text"],
)
);
Related
Sorry for the bad title, but I don't know how to create following JSON in PHP:
{
"id":"1",
"method":"getData",
"params":{
"options":{
"element":{
"id":"1a_ext",
"type":1,
"keyType":"externalkey"
},
"moreInfo":true,
"userFields":[
"id",
"name",
"longname",
"externalkey"
]
}
},
"jsonrpc":"2.0"
}
I don't know to do the part after "params" (how do I "put" options "into" params) - for the other parts I know what I have to do:
public static function getData(){
$json = array(
"id" => self::id(),
"method" => "getData",
"params" => array(
"id" => self::$userid,
"type" => self::$type
),
"jsonrpc" => "2.0"
);
$json = json_encode($json, true);
return self::request($json);
}
I would really appreciate your help, thanks!
You directly can assign to the params keys like
$json['params']['options'] = $your_options;
Full version of your code as an example
public static function getData(){
$json = array(
"id" => self::id(),
"method" => "getData",
"params" => array(
"id" => self::$userid,
"type" => self::$type
),
"jsonrpc" => "2.0"
);
# add something to param index
$json['params']['options'] = $your_options;
$json = json_encode($json, true);
return self::request($json);
}
You can create the this in array format in PHP and then JSON encode:
$arr = [
'id' => 1,
'method' => 'getData',
'params' => [
'options' => [
'element' => [
'id' => '1a_ext',
'type' => 1,
'keyType' => 'externalKey'
],
'moreInfo' => true,
'userFields' => [
'id',
'name',
'longname',
'externalKey'
]
]
],
'jsonrpc' => '2.0'
];
$json = json_encode($arr);
Instead of spoonfeeding, i would like to help related, Whenever if you find difficulties to create an array representation of a JSON then you should use var_export(array, true) the second parameter must be true to return the variable representation instead of outputting it
<?php
$json_str = '{
"id": "1",
"method": "getData",
"params": {
"options": {
"element": {"id": "1a_ext", "type": 1, "keyType": "externalkey"},
"moreInfo": true,
"userFields": ["id", "name", "longname", "externalkey"]
}
},
"jsonrpc": "2.0"
}';
$json_arr = var_export(json_decode($json_str, true), true);
print_r($json_arr);
check the output here https://paiza.io/projects/eUZZDsTsSFSM4m9WMl05Ow
$json_arr is an array representation for your JSON, now you can dynamic the array values
I am getting the JSON output below:
{
"clientCorrelator": "58a1acaf3ebf0",
"referenceCode": "REF-12345",
"endUserId": "263774705932",
"transactionOperationStatus": "Charged",
"paymentAmount": {
"0": {
"amount": 34,
"currency": "USD",
"description": "Ecofarmer Bulk Sms Online payment"
}
},
"chargeMetaData": {
"channel": "WEB",
"purchaseCategoryCode": "Online Payment",
"onBeHalfOf": "Paynow Topup"
},
"merchantCode": "42467",
"merchantPin": "1357",
"merchantNumber": "771999313"
}
I want to get the output below but somehow my php to JSON object conversion is turning the "charginginformation" key to "0".
$payment_amount = array(
$charginginformation = array(
'amount' => 34,
'currency' => 'USD',
'description' => 'Ecofarmer Bulk Sms Online payment'
)
);
$charge_data = array(
'channel' => 'WEB',
'purchaseCategoryCode' => 'Online Payment',
'onBeHalfOf' => 'Paynow Topup'
);
//API Url
$url = '';
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = array(
'clientCorrelator' => $u_id,
'referenceCode' => 'REF-12345',
'endUserId' => '263774705932',
'transactionOperationStatus' => 'Charged',
'paymentAmount' => $payment_amount,
'chargeMetaData' => $charge_data,
'merchantCode' => '42467',
'merchantPin' => '1357',
'merchantNumber' => '771999313'
);
//Encode the array into JSON.
$jsonDataEncoded = json_encode($jsonData, JSON_FORCE_OBJECT);
How can I stop the json_encode from changing the key?
Your issue is here:
$payment_amount = array(
//this is essentially array("cat", "dog", "etc");
$charginginformation = array(
'amount' => 34,
'currency' => 'USD',
'description' => 'Ecofarmer Bulk Sms Online payment'
)
);
You are adding an element to an array with a numeric index
To get this to work do
$payment_amount = array(
"charginginformation" => array(
//array data
)
);
I have integrated the Wepay payment gateway. But I have facing a problem to pass json object to wepay. It always shows a incorrect json format. Please look at the below code.
$forca_a = array(
'debit_opt_in'=>true
);
$forca = json_encode($forca_a,JSON_FORCE_OBJECT);
$wepay_create_array = array(
'name' =>"xxxx",
'description' => "xxxxxxxxx xxxx",
'callback_uri' => "xxxxxxx",
'country' => "CA",
'currencies' => array('CAD'),
'country_options' => $forca,
'rbits'=> array(
array(
'receive_time'=>strtotime("now"),
'type' =>'website_uri',
'source' => 'partner_database',
'properties'=> array('uri'=>xxxxx)
)
)
);
If I won't pass the country_options, its seems to working but If I pass this parameter, it always give me an error says "Incorrect JSON format".
I sent an email to wepay help center. They told me that, you are passing the string "country_options":"{"debit_opt_in":true}" <--- this is a string Instead of "country_options":{"debit_opt_in":true} <--- this is a JSON object. So I'm confused. I have no idea how do I pass the JSON object. There is only way and is json_encode($object).
hey use below code to get proper json
<?php
$forca_a = array(
'debit_opt_in'=>true
);
// $forca = json_encode($forca_a);
$wepay_create_array = array(
'name' =>"xxxx",
'description' => "xxxxxxxxx xxxx",
'callback_uri' => "xxxxxxx",
'country' => "CA",
'currencies' => array('CAD'),
'country_options' => $forca_a,
'rbits'=> array(
array(
'receive_time'=>strtotime("now"),
'type' =>'website_uri',
'source' => 'partner_database',
'properties'=> array('uri'=>'xxxxx')
)
)
);
print_r(json_encode($wepay_create_array));
?>
this code will give following json output
{
"name": "xxxx",
"description": "xxxxxxxxx xxxx",
"callback_uri": "xxxxxxx",
"country": "CA",
"currencies": ["CAD"],
"country_options": {
"debit_opt_in": true
},
"rbits": [{
"receive_time": 1461561030,
"type": "website_uri",
"source": "partner_database",
"properties": {
"uri": "xxxxx"
}
}]
}
You have no need to make:
$forca = json_encode($forca_a,JSON_FORCE_OBJECT);
before you put it to $wepay_create_array.
Before sending request, i think, you make json_encode($wepay_create_array), and yes, after that you will have 'string' for country_options key.
It says invalid json
{"userDetails": "RefId": 565521, {"key":[{"SNO":"565566","Type":"0","Desc":"0"},{"SNO":"12","Type":"1","Desc":"0"}]}, "success":true}
I want to add RefId while including it says invalid json please see and let me know whr m i wrong
You have not written it correctly:
{
"userDetails": [{
"RefId": 565521,
"key": [{"SNO":"565566","Type":"0","Desc":"0"},{"SNO":"12","Type":"1","Desc":"0"}],
"success" : true
}]
}
Your json should be like that :
{"userDetails": {"RefId": 565521, "key":[{"SNO":"565566","Type":"0","Desc":"0"},{"SNO":"12","Type":"1","Desc":"0"}]}, "success":true}
And you should generate it like that :
$resultJson = array(
'userDetails' => array(
'refId' => $reference_id,
'key' => $arr
),
'success' => true
);
echo json_encode($resultJson);
I'm working with API of a delivery service. They provide an opportunity to test the API on their website, where the following code works perfectly:
{
"modelName": "InternetDocument",
"calledMethod": "documentsTracking",
"methodProperties": {
"Documents": [
"20450000773554",
"20450000773555"
]
}
}
But when I try to convert it to PHP format, I don't know what to do with the arrays of 'methodProperties' in PHP syntax.
$data = array(
'modelName' => 'InternetDocument',
'calledMethod' => 'documentsTracking',
'methodProperties' => ???
);
Can you please help me to convert the code to PHP correctly?
You need to understand how json_encode and json_decode functions work:
This as JSON string:
{
"modelName": "InternetDocument",
"calledMethod": "documentsTracking",
"methodProperties": {
"Documents": [
"20450000773554",
"20450000773555"
]
}
}
is equivalent to this in PHP:
array(
'modelName' => 'InternetDocument',
'calledMethod' => 'documentsTracking',
'methodProperties' => array(
'Documents' => array(
"20450000773554",
"20450000773555"
)
)
);
Try that
<?php
$data = array(
'modelName' => 'InternetDocument',
'calledMethod' => 'documentsTracking',
'methodProperties' => array('Documents' => array('20450000773554', '20450000773554'))
);
echo json_encode($data);
?>
JSON :
$json = {
"modelName": "InternetDocument",
"calledMethod": "documentsTracking",
"methodProperties": {
"Documents": [
"20450000773554",
"20450000773555"
]
}
}
the data of this format is known as JSON(Javascript object notation),So,If you want to access it by using PHP you have to decode it using json_decode predefined function in PHP.
PHP:
$decoded_string = json_decode($json);
now use,
echo "<pre>";
print_r($decoded_string);
you get the following data in the form of array and you can easily parse this data in your application.
array(
'modelName' => 'InternetDocument',
'calledMethod' => 'documentsTracking',
'methodProperties' => array(
'Documents' => array(
"20450000773554",
"20450000773555"
)
)
);