I'm reading a json file using
$jsonStr = file_get_contents("connection.json");
$jsonParsed = json_decode($jsonStr,true);
and I want $jsonParsed to be a associative array like this:
$jsonParsed = { "SERVER" => "111.222.333.444" , "USER" => "edvaldo" , "PASSWORD" => "my_password_here", "DATABASE" => "my_database_here" };
What is the format of the JSON needed to do this?
I tried this
{
"SERVER": "111.222.333.444",
"USER": "edvaldo",
"PASSWORD": "my_password_here",
"DATABASE": "my_database_here"
}
but even with JSONLint saying this piece og JSON is valid, I can't get the result I need.
I'm not really very used to JSON and then I will appreciate a lot any help given.
EDITED:
This is the function I'm using:
private function set_mysql_parameters() {
$this->connectionParams = array();
$json_file = $this->system_paths["JSONDATA"] . "connection.json";
$json_mysql = file_get_contents($json_file);
$json_parsed = json_decode($json_file,true,250);
foreach($json_parsed as $key => $value) {
$this->connectionParams[$key] = $value;
}
}
My goal is to fill this array $this->connectionParams with data extracted from the JSON file.
I notice that you are trying to decode the filename instead of the content.
$json_file = $this->system_paths["JSONDATA"] . "connection.json";
$json_parsed = json_decode($json_file,true,250);
Shouldn't it be
$json_parsed = json_decode($json_mysql, true, 250);
Related
For a site I'm working on, a user has the option to input exercise data and it is saved to a JSON file in an array:
{
"Email": "chandlerbing#centralperk.com",
"ExerciseType": "Running",
"DistanceTravelled": "35",
},
But what I want it to do is to be able to save it in a multidimensional array so multiple records can be put in for one user.
Example:
{
"chandlerbing#centralperk.com"
{
"ExerciseType": "Running",
"DistanceTravelled": "35",
}
}
That way multiple records for the user are saved under one primary object to make it easier to access later. However I've never used multi-dimensional arrays before so I can't figure out how to modify my code to get this to work.
// Save data
$file = ('data.json');
$arr = array();
$new_userstats = array (
'Email' => $email,
'ExerciseType' => $exerciseType,
'DistanceTravelled' => $distance
);
$jsondata = file_get_contents($file);
$arr_data = json_decode($jsondata, true);
array_push($arr_data, $new_userstats);
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
file_put_contents($file,$jsondata);
If Email is the attribute to uniquely identify a user. It would be great to keep this as key of our array to easily find
and add a new data to existing file.
Now the format we would be storing in file looks like
{
"chandlerbing#centralperk.com" : [
{
"ExerciseType": "Running",
"DistanceTravelled": "35",
},
{
"ExerciseType": "Jogging",
"DistanceTravelled": "13",
},
],
"test#centralperk.com" : [
{
"ExerciseType": "Running",
"DistanceTravelled": "11",
},
]
}
Now how to add new data to this file would be in following way.
// Fetch existing data
$strFile = 'data.json';
$arrExistingData = json_decode(file_get_contents($strFile), true);
// Add new data to existing data, new data would contain and object in following way
$arrNewData = [
'ExerciseType' => $exerciseType,
'DistanceTravelled' => $distance
];
$arrExistingData[$email][] = $arrNewData;
// Save data back to file, avoid JSON_PRETTY_PRINT to reduce the file size.
file_put_contents($strFile, json_encode($arrExistingData));
Try:
$new_userstats = array (
$email => array (
'ExerciseType' => $exerciseType,
'DistanceTravelled' => $distance
)
);
I'm messing about with FB Messenger and trying to send a 'list' back, this has to be created with a mySQL lookup and loop.
The correct JSON to send back is defined on Facebook Developers here.
What I cannot understand is how with PHP I create the 'header' and 'footer' of the object, I have made a loop to put the main content into an array using my database results:
$messagePayload = array();
while($row = $result->fetch_assoc()) {
$messagePayloadC = array();
$messagePayloadC['title'] = $row['Name'].";
$messagePayloadC['item_url'] = $row['link'];
$messagePayloadC['image_url'] = $row['Image'];
$messagePayloadC['subtitle'] = "$".$row['Price'].";
$messagePayloadC['buttons']['type'] = "web_url";
$messagePayloadC['buttons']['url'] = $row['link'];
$messagePayloadC['buttons']['title'] = "Go!";
$messagePayload[] = $messagePayloadC;
}
echo var_dump(json_encode($messagePayload))."<p>";
What I need to do is add all of the missing peices at the start and end. The output of my array gives:
{"title":"My Television","item_url":"https:\/\/www.google.com\/","image_url":"product-image.jpg","subtitle":"$5","buttons":{"type":"web_url","url":"https:\/\/www.google.com\/","title":"Go!"}}
The missing header for example is:
"attachment": {
"type": "template",
"payload": {
"template_type": "list",
"top_element_style": "compact",
"elements": [
Am I going about this in the wrong way ?
I am struggled at this point.
I am using the script for inserting/updating website languages.
The main structure of the JSON file looks like this
{
"English": {
"shortcode": "EN"
}
}
Here is a sample of the code I am using to insert a language into my JSON file
$data['french'] = $_POST;
array_push($json, $data);
$jsonData = json_encode($json, JSON_PRETTY_PRINT);
file_put_contents(__DIR__.'/../files/lg.json', $jsonData);
But when I insert a new record into my JSON file new key appends in my JSON file and it looks like this,
{
"English": {
"shortcode": "EN"
},
"0": {
"French": {
"shortcode": "FR"
}
}
}
So my question is how can I insert a new record but to not insert the key "0", "1"..
Thanks in advance.
You only have to make $json[key] = value
$json['French'] = $_POST;
If it does not exist it is added, otherwise it is updated
It seems the $_POST is an array.
So you are pushing an array onto the $json array
Try this:
$json = $json + $_POST;
$jsonData = json_encode($json, JSON_PRETTY_PRINT);
file_put_contents(__DIR__.'/../files/lg.json', $jsonData);
I have the following data from an api call:
$userId = 1234; and $accessToken = 6789;. I want to write this to a json file called users.json.
Following this I make another api call and receive the following data:
$userId = 5678; and $accessToken = 0123;.
I then want to add this to the json file so that it looks like this:
[
{
"userId": "1234",
"accessToken": "6789"
},
{
"userId": "5678",
"accessToken": "0123"
},
]
My code for writing to the json file looks like this. The $userId and $accessToken are defined elsewhere and are returning the correct values:
$content = file_get_contents('users.json');
$tempArray = json_decode($content, true);
print_r($tempArray); // this doesn;t show anything as the users.json file contains `null`
array_push($tempArray, $userId);
array_push($tempArray, $accessToken);
$jsonData = json_encode($tempArray);
file_put_contents('users.json', $jsonData);
Unfortunately this isn't working. When I view the json file it just contains null Can anyone see any error with my code?
Thanks Raul
Your code is wrong. Correct it to look like this
<?php
$content = file_get_contents('users.json');
$tempArray = json_decode($content, true);
if(empty($tempArray)){
$tempArray = [];
}
$newData = [
"userId" => $userId,
"accessToken" => $accessToken
];
array_push($tempArray, $newData);
$jsonData = json_encode($tempArray);
file_put_contents('users.json', $jsonData);
This will definitely work.
You need to to json_decode($content, true); to obtain an array and not an object.
See http://php.net/manual/fr/function.json-decode.php
Also the array_push is not correctly called.
It should be : array_push($tempArray, ["userid"=>$userId,"accesstoken" => $accessToken]);
You have error in json file so that all suggesion not working remove , at end of array. Then try below code :
Your json file should be:
[
{
"userId": "1234",
"accessToken": "6789"
},
{
"userId": "5678",
"accessToken": "0123"
}
]
php :
$content = file_get_contents('user.json');
$tempArray = json_decode($content,true);
$new_array = array("userId"=>$userId,"accesstoken"=>$accessToken);
array_push($tempArray, $new_array);
$jsonData = json_encode($tempArray);
file_put_contents('user.json', $jsonData);
This question already has answers here:
How to loop through PHP object with dynamic keys [duplicate]
(16 answers)
Closed 5 years ago.
This is my JSON.
{
"OUT_STAT": "200",
"OUT_MESS": "SUKSES",
"OUT_DATA": [{
"id_doc_proj": "4"
}]
}
My Questions are:
1. How to get OUT_STAT value?
2. How to get id_doc_proj value?
I am sorry if my questions are silly because i am new at get value from JSON.
Thanks in advance.
UPDATE
I am sorry if you are saying i duplicated Parsing JSON file with PHP. I have tried code from there but i don't get any JSON from my response. I don't know where is the mistake. If you want to help, this is my php script.
<?php
$file_path = "";
$id_project = "16";
$p_id_doc_proj = "50";
$id_doc_type = "1";
$id_user = "4";
$url = $file_path.basename($_FILES['uploaded_file']['name']);
if(move_uploaded_file($_FILES['uploaded_file']['tmp_name'], $url)){
$ws = "http://172.xx.x.xx:xxxx/rest/com/acc/uw/in/httprest/apponline/uploadtrough/UploadImage/$id_project/$p_id_doc_proj/$id_doc_type/$id_user/$url";
$opts = array('http'=>array('header'=>'Content-type: application/x-www-form-urlencoded'));
$context = stream_context_create($opts);
$arrayLog=array();
$data1 = file_get_contents($ws, false, $context);
$result = json_decode($data1, true);;
//$result = array("result" => "success");
}else{
$result = array("result" => "error");
}
echo json_encode($result);
?>
The result should show my JSON above but it was null. Any answers will help me. Thanks in advance.
$data="{
"OUT_STAT": "200",
"OUT_MESS": "SUKSES",
"OUT_DATA": [{
"id_doc_proj": "4"
}]
}";
$op=json_decode($data, true);
echo $op['OUT_STAT'];
echo $op['OUT_DATA'][0]['id_doc_proj'];
http://php.net/json_deocde. it will make output as associative array. you can then use the result as you would do with an assoc array. you can also use var_dump() to introspect the structure.
you can use json_decode to convert json to array or object:
$json = '{
"OUT_STAT": "200",
"OUT_MESS": "SUKSES",
"OUT_DATA": [{
"id_doc_proj": "4"
}]
}';
$object = json_decode($json);
$out_stat = $object->OUT_STAT;
$id_doc_proj = $object->OUT_DATA[0]->id_doc_proj;