My JSON data is given below. It does not have [] or separated by comma which make it difficult for me to decode.
$jsondata =
'{"firstname": "user1", "lastname": "user1", "phonenumber": "12314", "notes": "[]", "lastvisited": "2021-05-12 21:49:15"}
{"firstname": "user2", "lastname": "user2", "phonenumber": "12345", "notes": "[]", "lastvisited": "2021-04-24 20:48:58"}';
My try:
$jsonans = json_decode($jsondata, true);
print_r($jsonans);
Any code suggestion is appreciated.
Thanks,
Your best bet is to get valid JSON. If this was stored somewhere as invalid and these are the only problems then just fix them:
$jsondata = '['.preg_replace('/}\s+{/', '}, {', $jsondata).']';
$result = json_decode($jsondata, true);
If you're sure that there is only one space between } and { then faster than regex:
$jsondata = '['.str_replace('} {', '}, {', $jsondata).']';
Then just loop $result and https://www.php.net/manual/en/function.fputcsv.php
Related
I'm trying to put a users "favourite" game into the corresponding file for their user upon post.
if(isset($_POST['favourite'])){
$filetxt = 'data/users.json';
$formdata = $_POST['favourite']; //this contains the value "game"
$arr_data = array();
if(file_exists($filetxt)) {
$jsondata = file_get_contents($filetxt);
$arr_data = json_decode($jsondata, true);
}
$arr_data[][$_SESSION['username']]['favourite'] = $formdata;
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
file_put_contents('data/users.json', $jsondata);
}
The file is structured as:
[
{
"CNR": {
"first-name": "test",
"last-name": "test",
"email": "test",
"country": "test",
"password": "test",
"favourite": []
}
},
{
"usertest": {
"first-name": "test",
"last-name": "test",
"email": "test",
"country": "United States",
"password": "password",
"favourite": []
}
}
]
Currently it will add the correct data however not into the array, but onto the end.
[
{
"CNR": {
"first-name": "test",
"last-name": "test",
"email": "test",
"country": "test",
"password": "test",
"favourite": []
}
},
{
"usertest": {
"first-name": "test",
"last-name": "test",
"email": "test",
"country": "United States",
"password": "password",
"favourite": []
}
},
{
"CNR": {
"favourite": "game"
}
}
]
I've tried things like arraypush, splice and other methods however I'm not sure what is the best for this use case.
Any thoughts/recommendations on how I can best achieve this with the desired result are greatly appreciated, thanks!
$arr_data[$_SESSION['username']]['favourite'][] = $formdata;
Difference is that I moved [] to the end of the $arr_data.
Before adding it to array, you need to check if the key exists and then proceed rather than just adding the code.
if(isset($_POST['favourite'])){
$filetxt = 'data/users.json';
$formdata = $_POST['favourite']; //this contains the value "game"
$arr_data = array();
if(file_exists($filetxt)) {
$jsondata = file_get_contents($filetxt);
$arr_data = json_decode($jsondata, true);
}
// changes over here
if(isset($arr_data[$_SESSION['username']])){
if(isset($arr_data[$_SESSION['username']]['favourite'])){
$arr_data[$_SESSION['username']]['favourite'][] = $formdata;
} else {
$arr_data[$_SESSION['username']]['favourite'] = $formdata;
}
} else {
$arr_data[][$_SESSION['username']]['favourite'] = $formdata;
}
$jsondata = json_encode($arr_data, JSON_PRETTY_PRINT);
file_put_contents('data/users.json', $jsondata);
}
I can see that most have answered the question but might I also provide some suggestions (food for thought) on your process?
1). Firstly, I can't work out if you are storing ALL users in a single file or if there's a file per user. Example username.json
I am going to assume there is a file per username because there should be to make file writes quicker and it would require the main file to be locked for everyone else just because one user is writing to it.
2). I noticed that the favourite part seems to be stored in the _SESSION too. If the _SESSION is storing the same mini array in it (a replica of what is stored in the file) then there's no point in opening the file to write a single value and then save it again. You may as well just write over the existing file straight away. Like this...
$writeToFile = json_encode($_SESSION[mydata]);
$fh = fopen("/path/to/username.json","w+");
fwrite($fh,$writeToFile);
fclose($fh);
// You could also use file_put_contents but most prefer
// to use fopen()
3). I will assume the passwords you are storing are encrypted and nobody can type [yourdomain]/users/username.json to see the raw output of the json files. You might want to ensure .json files aren't accessible from the browser. You can do that with .htaccess.
Problem is in this code, you are creating every time a new sub array:
Change this:
$arr_data[][$_SESSION['username']]['favourite'] = $formdata;
To this
if(isset($arr_data[$_SESSION['username']])) {
$arr_data[$_SESSION['username']]['favourite'] = $formdata;
}
I have a string that i get from an API and i wish i could put it in a array so i could check the values that came from the return.
String return example:
{
"code":"000",
"message":"XXX",
"date":"2018-05-17",
"hour":"09:16:09",
"revision":"",
"server":"XX",
"content":{
"nome":{"info":"SIM","conteudo":[{"field1":"XXXX","field2":"XX"}]}
}
}
What I need:
echo $string['code'];
Javascript has no problem with JSON encode command. But how can I do it with PHP?
First of all your JSON data seems to be invalid (Some brackets missing). It needs to be like this:-
{
"code": "000",
"message": "XXX",
"date": "2018-05-17",
"hour": "09:16:09",
"revision": "",
"server": "XX",
"content": {
"nome": {
"info": "SIM",
"conteudo": [{
"field1": "XXXX",
"field2": "XX"
}]
}
}
}
Now You need to decode this JSON data and then get data based on the index
$array = json_decode($json,true);
echo $array['code'];
Output:-https://eval.in/1005949
You can decode the JSON string to Array in PHP.
$str = '{"code":"000","message":"XXX","date":"2018-05-17","hour":"09:16:09","revision":"","server":"XX","content":{"nome":{"info":"SIM","conteudo":[{"field1":"XXXX","field2":"XX"}]}';
$decodedValue = json_decode($str, true);
var_dump($decodedValue);
Your example string is not valid json, you are missing some closing brackets.
This should be the correct way:
'{"code":"000","message":"XXX","date":"2018-05-17","hour":"09:16:09","revision":"","server":"XX","content":{"nome":{"info":"SIM","conteudo":[{"field1":"XXXX","field2":"XX"}]}}}'
As for your question. in PHP you can easily use json_decode
Example:
<?php
$json = '{"code":"000","message":"XXX","date":"2018-05-17","hour":"09:16:09","revision":"","server":"XX","content":{"nome":{"info":"SIM","conteudo":[{"field1":"XXXX","field2":"XX"}]}}}';
$decoded_json = json_decode($json, true);
echo $decoded_json['code'];
You can see it working here
I have JSON Object which I have encoded like so
{
"id": "",
"steps": [
{
"target": "purchase_order_items_itemmaster_id",
"title": "",
"placement": "",
"content": "",
"xoffset": "",
"yoffset": ""
}
]
}
$JSONData = json_encode($finalData,JSON_PRETTY_PRINT);
I am taking this JSON data and storing it in a file like so
File::put("path","var tour = \n [ \n\t $JSONData \n ];");
which looks something like this in the file
var tour =
[
{
"id": "",
"steps": [
{
"target": "purchase_order_items_itemmaster_id",
"title": "",
"placement": "",
"content": "",
"xoffset": "",
"yoffset": ""
}
]
}
];
Now I am reading it back form the second line like so
[
{
"id": "",
"steps": [
{
"target": "purchase_order_items_itemmaster_id",
"title": "",
"placement": "",
"content": "",
"xoffset": "",
"yoffset": ""
}
]
}
];
The problem is when I want to decode it back it doesn't happen,this is how I am trying to do that,
$lines = file_get_contents("path",NULL,NULL,10);
$a = json_decode($lines);
Now according to expected output the $a should have the decoded data but it has null.
Can someone point out the mistake?
I believe the issue is the semicolon at the end of the JSON you've read back in from the file. Try chopping that off before attempting json_decode:
$a = json_decode(rtrim($lines, ";"));
pass the second parameter true for recursively decoding
$a = json_decode(chop($lines,";"),true);
check the php mannual here json_decode
It will be
$str = file_get_contents('http://example.com/example.json/');
$json = json_decode($str, true); // decode the JSON into an associative array
See the post
Parsing JSON file with PHP
try to save data in file like
$fp = fopen('path', 'w');
fwrite($fp, json_encode($JSONData)); //if $JSONData is in string
fclose($fp);
instead of
File::put("path","var tour = \n [ \n\t $JSONData \n ];");
//and read like
// Read JSON file
$json = file_get_contents('path');
//Decode JSON
$json_data = json_decode($json,true);
//Print data
print_r($json_data);
I am trying to take a json object stored in a textarea and convert it into a php array. I assign the value of the textarea to variable like $data = $_POST[‘data’] . When I submit the value of the text I use json_decode($data, true) to convert from JSON Object to php array. But nothing happens. It seems like nothing is assigned. How can I achieve the above?
EDIT: I have added quotes and made the suggestion below and is not working: DEMO
PHP
if(isset($_POST['submit'])) {
$data = $_POST['data'];
$personArray = json_decode($data, true);
print_r($personArray);
}
HTML
<textarea name="data">[{
"firstName": "Jenny",
"lastName": "LaRusso",
"phone": "(555) 121-2121",
"alt_phone": "(555) 123-4567",
"main1": false,
"main2": true
}, {
"firstName": "Sensei",
"lastName": "Miyagi",
"phone": "(555) 444-2222",
"alt_phone": "(555) 999-1212",
"main1": true,
"main2": false
}]</textarea>
I think in proper JSON, the keys (like firstName) need also be enclosed in quotes.
Change your PHP code to
if(isset($_POST['data'])) {
$data = $_POST['data'];
$data = stripslashes($data); //Stripslashes removes all backslashes :)
$personArray = json_decode($data, true);
print_r($personArray);
}
Your JSON object should be this way inside the textarea
[{
"firstName": "Jenny",
"lastName": "LaRusso",
"phone": "(555) 121-2121",
"alt_phone": "(555) 123-4567",
"main1": false,
"main2": true
}, {
"firstName": "Sensei",
"lastName": "Miyagi",
"phone": "(555) 444-2222",
"alt_phone": "(555) 999-1212",
"main1": true,
"main2": false
}]
Happy Coding :)
There does not seem to be anything wrong with your PHP code.
For debugging, after setting $personArray, try adding these two lines:
var_dump($data);
var_dump($personArray);
This should lead to why you are having trouble.
Here you can see what each return type means(if $returnArray is equal to false): http://php.net/json_decode
I tried to request the weather from a web service supplying data in JSON format. My PHP request code, which did not succeed was:
$url="http://www.worldweatheronline.com/feed/weather.ashx?q=schruns,austria&format=json&num_of_days=5&key=8f2d1ea151085304102710";
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
echo $data[0]->weather->weatherIconUrl[0]->value;
This is some of the data that was returned. Some of the details have been truncated for brevity, but object integrity is retained:
{ "data":
{ "current_condition":
[ { "cloudcover": "31",
... } ],
"request":
[ { "query": "Schruns, Austria",
"type": "City" } ],
"weather":
[ { "date": "2010-10-27",
"precipMM": "0.0",
"tempMaxC": "3",
"tempMaxF": "38",
"tempMinC": "-13",
"tempMinF": "9",
"weatherCode": "113",
"weatherDesc": [ {"value": "Sunny" } ],
"weatherIconUrl": [ {"value": "http:\/\/www.worldweatheronline.com\/images\/wsymbols01_png_64\/wsymbol_0001_sunny.png" } ],
"winddir16Point": "N",
"winddirDegree": "356",
"winddirection": "N",
"windspeedKmph": "5",
"windspeedMiles": "3" },
{ "date": "2010-10-28",
... },
... ]
}
}
}
This appears to work:
$url = 'http://www.worldweatheronline.com/feed/weather.ashx?q=schruns,austria&format=json&num_of_days=5&key=8f2d1ea151085304102710%22';
$content = file_get_contents($url);
$json = json_decode($content, true);
foreach($json['data']['weather'] as $item) {
print $item['date'];
print ' - ';
print $item['weatherDesc'][0]['value'];
print ' - ';
print '<img src="' . $item['weatherIconUrl'][0]['value'] . '" border="0" alt="" />';
print '<br>';
}
If you set the second parameter of json_decode to true, you get an array, so you cant use the -> syntax. I would also suggest you install the JSONview Firefox extension, so you can view generated json documents in a nice formatted tree view similiar to how Firefox displays XML structures. This makes things a lot easier.
If you use the following instead:
$json = file_get_contents($url);
$data = json_decode($json, TRUE);
The TRUE returns an array instead of an object.
Try this example
$json = '{"foo-bar": 12345}';
$obj = json_decode($json);
print $obj->{'foo-bar'}; // 12345
http://php.net/manual/en/function.json-decode.php
NB - two negatives makes a positive . :)
Seems like you forgot the ["value"] or ->value:
echo $data[0]->weather->weatherIconUrl[0]->value;
When you json decode , force it to return an array instead of object.
$data = json_decode($json, TRUE); -> // TRUE
This will return an array and you can access the values by giving the keys.
You have to make sure first that your server allow remote connection so that the function file_get_contents($url) works fine , most server disable this feature for security reason.
While editing the code (because mild OCD), I noticed that weather is also a list. You should probably consider something like
echo $data[0]->weather[0]->weatherIconUrl[0]->value;
to make sure you are using the weatherIconUrl for the correct date instance.