I have a trouble with JSON in PHP.
I have a JSON structure like this (with some line is const and some line is variable)
{
"user": {
"lam": {---->variable
"\/lam\/files\/a": { ---->variable
"id": 9, ---->variable
"class": "\\OC\\Files\\Storage\\Swift",
"options": {
"user": "owncloud",
"bucket": "lam-15215156681752265498", ---->variable
"password": "",
"region": "regionOne",
"service_name": "swift",
"tenant": "owncloud",
"timeout": "30",
"url": "http:\/\/controller:5000\/v2.0",
"password_encrypted": "NHBuZHd4azhvZDB6b29oYSu5U7JLrDC3AdZGykzNpDU=" ---->variable
}
}
}
}
}
I don't know how to write this content to file as JSON format like this.
And in a number of case, I must write append to this file and result must like this:
{
"user": {
"lam": {
"\/lam\/files\/a": {
"id": 9,
"class": "\\OC\\Files\\Storage\\Swift",
"options": {
"user": "owncloud",
"bucket": "lam-15215156681752265498",
"password": "",
"region": "regionOne",
"service_name": "swift",
"tenant": "owncloud",
"timeout": "30",
"url": "http:\/\/controller:5000\/v2.0",
"password_encrypted": "NHBuZHd4azhvZDB6b29oYSu5U7JLrDC3AdZGykzNpDU="
}
},
"\/lam\/files\/test": {
"id": 12,
"class": "\\OC\\Files\\Storage\\Swift",
"options": {
"user": "owncloud",
"bucket": "lam-152153961597103330",
"password": "",
"region": "regionOne",
"service_name": "swift",
"tenant": "owncloud",
"timeout": "30",
"url": "http:\/\/controller:5000\/v2.0",
"password_encrypted": "MjdzcDlrenptcG5udzI2MLSQvuGIczY\/SyHZVf9o7e8="
}
}
}
}
}
You could create an array, before to use json_encode():
Here is an example.
// prepare an array with variable (should come from database, or whatever)
$vars = [
[
'user' => 'lam',
'path' => '/lam/files/a',
'id' => 9,
'bucket' => 'lam-15215156681752265498',
'pass' => 'NHBuZHd4azhvZDB6b29oYSu5U7JLrDC3AdZGykzNpDU=',
],
[
'user' => 'lam',
'path' => '/lam/files/test',
'id' => 12,
'bucket' => 'lam-152153961597103330',
'pass' => 'MjdzcDlrenptcG5udzI2MLSQvuGIczY/SyHZVf9o7e8=',
]
];
// prepare data to be encoded.
$data = [];
// iterate over the variables,
foreach ($vars as $var) {
// prepare an array for the options
$options = [
"user" => "owncloud",
"bucket" => $var['bucket'], // fill with current variable
"password" => "",
"region" => "regionOne",
"service_name" => "swift",
"tenant" => "owncloud",
"timeout" => "30",
"url" => "http:\/\/controller:5000\/v2.0",
"password_encrypted" =>$var['pass'], // fill with current variable
];
$userdata = [
'id' => $var['id'], // fill with current variable
'class' => '\\OC\\Files\\Storage\\Swift',
'options' => $options, // append options
];
$name = $var['user'];
$path = $var['path'];
$data['user'][$name][$path] = $userdata ; // append to $data array
}
echo json_encode($data, JSON_PRETTY_PRINT);
Outputs:
{
"user": {
"lam": {
"\/lam\/files\/a": {
"id": 9,
"class": "\\OC\\Files\\Storage\\Swift",
"options": {
"user": "owncloud",
"bucket": "lam-15215156681752265498",
"password": "",
"region": "regionOne",
"service_name": "swift",
"tenant": "owncloud",
"timeout": "30",
"url": "http:\\\/\\\/controller:5000\\\/v2.0",
"password_encrypted": "NHBuZHd4azhvZDB6b29oYSu5U7JLrDC3AdZGykzNpDU="
}
},
"\/lam\/files\/test": {
"id": 12,
"class": "\\OC\\Files\\Storage\\Swift",
"options": {
"user": "owncloud",
"bucket": "lam-152153961597103330",
"password": "",
"region": "regionOne",
"service_name": "swift",
"tenant": "owncloud",
"timeout": "30",
"url": "http:\\\/\\\/controller:5000\\\/v2.0",
"password_encrypted": "MjdzcDlrenptcG5udzI2MLSQvuGIczY\/SyHZVf9o7e8="
}
}
}
}
}
You'll need to work with the data as an array (or object) as PHP won't work directly in JSON;
Get your current data from the file into an array:
$data = json_decode(file_get_contents($pathtojsonfile, true));
Append the new data to the array:
$data[] = $newdata;
Then save the newly appended data back to file.
file_put_contents($pathtojsonfile, json_encode($data));
Related
I have a problem with my web service response and i'm not able to fix this problem.
So i want to get a result with letter data in Uppercase, cause after that I don't able to see my informations.
Here this my code on web service :
/**
* #Route("/contact/getContactFilter/{tdlinx}/{soc}", name="contact_getContactFilter")
*/
public function getContactFilter($tdlinx, $soc){
$em = $this->getDoctrine()->getManager("APP_REFERENTIEL");
$contactFilter = $em -> getRepository(CONTACT::class)->findBy(["TDLINX" => $tdlinx,"SOCIETE" => $soc,"ACTIF" => 1]);
$encoders = [new JsonEncoder()]; // If no need for XmlEncoder
$normalizer = new ObjectNormalizer();
$normalizers = [new \App\Utils\DateTimeNormalizer(), $normalizer];
$serializer = new Serializer($normalizers, $encoders);
$jsonObject = $serializer->serialize($arrayUpper, 'json', [
'circular_reference_handler' => function ($object) {
return $object->getId();
}]);
if(!$contactFilter) return new Response(null,204);
else return new Response($jsonObject,200, ['Content-Type' => 'application/json']);
}
And this is my response on Postman and the problem is visible here at third part :
{
"id": 63,
"TDLINX": 257242,
"TYPE": "physique",
"SOCIETE": "B",
"NOM": "Post",
"PRENOM": "Strike",
"COMMENTAIRE": "Test",
"ACTIF": true,
"INFOS": [
{
"id": 52,
"VALUE": "006516451",
"CONTACTID": 63,
"TYPEID": {
"id": 15,
"lIBELLE": "Phone fixe",
"pATTERN": "phone",
"sOCIETE": "B",
"iCON": "local_phone",
"lIST": [],
"iNFOS": [
{
"id": 51,
"VALUE": "034455258",
"CONTACTID": {
"id": 169,
"tDLINX": 257242,
"tYPE": "physique",
"sOCIETE": "B",
"nOM": "Norris",
"pRENOM": "Chuck",
"cOMMENTAIRE": "Test",
"aCTIF": false,
"iNFOS": [
{
"id": 50,
"VALUE": "Directeur adjoint",
"CONTACTID": 169,
"TYPEID": {
"id": 17,
"lIBELLE": "Poste",
"pATTERN": "liste",
"sOCIETE": "B",
"iCON": "business_center",
"lIST": [
{
"id": 12,
"VALUE": "Directeur",
"TYPEID": 17
},
{
"id": 13,
"VALUE": "Directeur adjoint",
"TYPEID": 17
},
{
"id": 14,
"VALUE": "Chef de rayon",
"TYPEID": 17
}
],
"iNFOS": [
50,
{
"id": 53,
"VALUE": "Directeur adjoint",
"CONTACTID": 63,
"TYPEID": 17
}
],
"__initializer__": null,
"__cloner__": null,
"__isInitialized__": true
}
},
51
],
"__initializer__": null,
"__cloner__": null,
"__isInitialized__": true
},
"TYPEID": 15
},
52
],
"__initializer__": null,
"__cloner__": null,
"__isInitialized__": true
}
}
}```
How to fix this problem ?
Please check your database probably you defined id as "id"(first letter in small letter)
I want JSON object as follows in that personal, address and itm have sequence of json object.
{
"id": "1",
"state": "12",
"personal": [
{
"name": "abc",
"contact":"1111111"
"address": [
{
"line1": "abc",
"city": "abc",
"itm": [
{
"num": 1,
"itm_detatils": {
"itemname": "bag",
"rate": 1000,
"discount": 0,
}
}
],
"status": "Y"
}
]
}
]
}
But I am getting result as follows in that I want json array at address and itm_details.
{
"id": "1",
"state": "12",
"personal": [
{
"name": "abc",
"contact": "1111111",
"address": {
"line1": "abc",
"city": "abc",
"itm": {
"inum": "1",
"itm_detatils": {
"itemname": "bag",
"rate": 1000,
"discount": 0
}
},
"status": "Y"
}
}
]
}
My PHP Code is as follow:
In that I am creating simple array and after that array inside array but during encoding to json it's not showing sequence of json object.
$a=array();
$a["id"]="1";
$a["state"]="12";
$a["personal"]=array();
$a["personal"][]=array(
"name"=>"abc",
"contact"=>"1111111",
"address"=>array(
"line1"=>"abc",
"city"=>"abc",
"itm"=>array(
"inum"=>"1",
"itm_detatils"=>array(
"itemname"=>"bag",
"rate"=>1000,
"discount"=>0,
),
),
"status"=>"Y",
),
);
echo json_encode($a);
Thanks in advance.
Add one more array
//...
"address" => array(
array(
"line1"=>"abc",
"city"=>"abc",
// ...
),
)
For 24hrs I have been really struggling to find how to access the email and address fields. I think I've tried every combination there is
my last attempt
$obj = json_decode($json);
$emails = $obj->emails->address;
JSON OUTPUT
{
"#http_status_code": 200,
"#visible_sources": 1,
"#available_sources": 1,
"#search_id": "1507310336407868146373527620323253083",
"query": {
"emails": [
{
"address": "paulsparktest#googlemail.com",
"address_md5": "d92590f691eab834586686c563567382"
}
]
},
"possible_persons": [
{
"#search_pointer": "3984f5b332b6efb3331bb137e1e97829ddff0971d9de9347cbd7fb8f82dc68de093a525a66584694339bfe580baff2aacb77954e0f154a1d0bd0a36588094972a72c1c4a63197a9736f6c425afdf66e5d8e52d35073d6499036efe9a234dd1d886f71bf54b9911a19725f118b6cd7bca521c246fe3b890a957596f8236c3c4ac5ba241198c3bdfa2f44a4e361393f1bf407130ffb5b9e2f6b1ccffca87befd0b147e51a12a54773ca31fc1a364b8cde876ca5f42b5d6f0c319f18300cab29fc1",
"names": [
{
"first": "Paul",
"last": "Johnson",
"display": "Paul Johnson"
}
],
"usernames": [
{
"content": "pauljohnson111"
}
],
"gender": {
"#inferred": true,
"content": "male"
},
"addresses": [
{
"country": "GB",
"state": "ENG",
"city": "London",
"display": "London, England"
}
],
"user_ids": [
{
"content": "374967130#twitter"
}
],
"images": [
{
"url": "http://pbs.twimg.com/profile_images/1546592694/Roccc.jpg",
"thumbnail_token": "AE2861B242686E7DDBDF0D814A3486E1D19BE9609F41B4AA71B6D0FEB03454A84C36C69AC788EF676B93C5274D29CD76361050E1F057871D&dsid=39844"
}
]
}
]
}
This will get the address for you
$obj->query->emails[0]->address;
if you want to iterate and get other addresses
foreach ( $obj->query->emails as $email ) {
echo $email->address;
}
You can get address & name via follow code.
// Getting email
echo $data->query->emails[0]->address;
// Getting name
echo $data->possible_persons[0]->names[0]->display;
Full code
$data = '{
"#http_status_code": 200,
"#visible_sources": 1,
"#available_sources": 1,
"#search_id": "1507310336407868146373527620323253083",
"query": {
"emails": [
{
"address": "paulsparktest#googlemail.com",
"address_md5": "d92590f691eab834586686c563567382"
}
]
},
"possible_persons": [
{
"#search_pointer": "3984f5b332b6efb3331bb137e1e97829ddff0971d9de9347cbd7fb8f82dc68de093a525a66584694339bfe580baff2aacb77954e0f154a1d0bd0a36588094972a72c1c4a63197a9736f6c425afdf66e5d8e52d35073d6499036efe9a234dd1d886f71bf54b9911a19725f118b6cd7bca521c246fe3b890a957596f8236c3c4ac5ba241198c3bdfa2f44a4e361393f1bf407130ffb5b9e2f6b1ccffca87befd0b147e51a12a54773ca31fc1a364b8cde876ca5f42b5d6f0c319f18300cab29fc1",
"names": [
{
"first": "Paul",
"last": "Johnson",
"display": "Paul Johnson"
}
],
"usernames": [
{
"content": "pauljohnson111"
}
],
"gender": {
"#inferred": true,
"content": "male"
},
"addresses": [
{
"country": "GB",
"state": "ENG",
"city": "London",
"display": "London, England"
}
],
"user_ids": [
{
"content": "374967130#twitter"
}
],
"images": [
{
"url": "http://pbs.twimg.com/profile_images/1546592694/Roccc.jpg",
"thumbnail_token": "AE2861B242686E7DDBDF0D814A3486E1D19BE9609F41B4AA71B6D0FEB03454A84C36C69AC788EF676B93C5274D29CD76361050E1F057871D&dsid=39844"
}
]
}
]
}';
$data = json_decode($data);
// Getting email
echo $data->query->emails[0]->address;
// Getting name
echo $data->possible_persons[0]->names[0]->display;
I have some data like this
"name": "abc",
"adr": "bcd",
"partners": {
"101": {
"name": "xyz.com",
"prices": {
"1001": {
"description": "Single Room",
"amount": 125,
"from": "2012-10-12",
"to": "2012-10-13"
},
"1002": {
"description": "Double Room",
"amount": 139,
"from": "2012-10-12",
"to": "2012-10-13"
}
}
Now, I have to write a json with all this data and use it as a data source.
How can I do it ?
The data you posted is not valid JSON. It misses some surrounding and ending brackets.
Ok, let's fix that... and save it as data.json:
{
"name": "abc",
"adr": "bcd",
"partners": {
"101": {
"name": "xyz.com",
"prices": {
"1001": {
"description": "SingleRoom",
"amount": 125,
"from": "2012-10-12",
"to": "2012-10-13"
},
"1002": {
"description": "DoubleRoom",
"amount": 139,
"from": "2012-10-12",
"to": "2012-10-13"
}
}
}
}
}
To access the JSON with PHP you can simply load the file and convert the JSON to an array.
<?php
$jsonFile = "data.json"
$json = file_get_contents($jsonFile);
$data = json_decode($json, TRUE);
echo "<pre>";
print_r($data);
echo "</pre>";
?>
A PHP Script to create a file containing this data as json
// the data you need
$phpData = [
"name" => "abc",
"adr" => "bcd",
"partners" => [
"101" => [
"name" => "xyz.com",
"prices" => [
"1001" => [
"description" => "Single Room",
"amount" => 125,
"from" => "2012-10-12",
"to" => "2012-10-13",
],
"1002" => [
"description" => "Double Room",
"amount" => 139,
"from" => "2012-10-12",
"to" => "2012-10-13",
]
]
]
]
];
// json_encode() that data to a string
$jsonData = json_encode($phpData);
// write that string to your file
file_put_contents('myJsonFile.json', $jsonData);
And to use it as a datasource
$myData = json_decode(
file_get_contents('myJsonFile.json')
);
I have this JSON code:
{
"phrases": [
{
"phrases": [
{
"id": "33",
"text": "sasdsad",
"date": "2012-03-14 20:28:45",
"views": "0",
"ip": "64.191.90.5",
"reported": "0",
"strange": "0",
"lang": "en"
},
{
"id": "32",
"text": "que ondaa\r\n",
"date": "2012-03-14 20:27:45",
"views": "0",
"ip": "64.191.90.5",
"reported": "0",
"strange": "0",
"lang": "en"
},
{
"id": "31",
"text": "dsadssadsad",
"date": "2012-03-14 20:27:35",
"views": "0",
"ip": "64.191.90.5",
"reported": "0",
"strange": "0",
"lang": "en"
}
],
"details": {
"success": "true",
"phrase_id": "",
"phrase_text": "",
"phrase_date": ""
}
}
I don't really know what to do. I get some phrases vía MySQL, and pushes them to an array. This array is json_encoded() and gets printed.
$sth = $sql;
$rows = array();
while($r = mysql_fetch_assoc($sth)) {
$rows[] = $r;
}
$sth = $sql;
$data = array(
"success" => "true",
"phrase_id" => "",
"phrase_text" => "",
"phrase_date" => "",
);
print json_encode($rows).json_encode($data);
and with jQuery I was trying to parse it, but I can't. This is the main problem.
function getPhrases(order,limit,last){
var req_url = ...;
$.getJSON(req_url, function(data) {
$.each(data.phrases, function(i, data) {
appendPhrase(data.text);
lastid = data.id;
});
$.each(data.details, function(i, data) {
$("#phrases-count").html(data.totalcount);
});
});
}
PS: I was doing this with "echo" but got some problems.
{
"phrases": [
{
"id": "33",
"text": "sasdsad",
"date": "2012-03-14 20:28:45",
"views": "0",
"ip": "64.191.90.5",
"lang": "en"
},
{
"id": "32",
"text": "que ondaa<br />",
"date": "2012-03-14 20:27:45",
"views": "0",
"ip": "64.191.90.5",
"lang": "en"
},
{
"id": "31",
"text": "dsadssadsad",
"date": "2012-03-14 20:27:35",
"views": "0",
"ip": "64.191.90.5",
"lang": "en"
}
],
"details": [
{
"totalcount": "3",
"logged_in": "false"
}
]
}
You can't simply combine these JSON arrays:
print json_encode($rows).json_encode($data);
Try this (attempt 2):
print json_encode( array('phrases' => $rows, 'details' => $data) );