i created a simple modifier to decode a string that is encoded in json.
function smarty_modifier_json_decode($string)
{
return json_decode($string, true);
}
Now i have somewhere into my database a string like this:
[{"foo": "bar bar", "cool": "attr"},{"foo": "bar", "cool": "attr"},{"foo": "bar", "cool": "attr"}]
The problem is the following if i store the above string locally inside the php file in a string variable and after i run the json_decode i get back the array i should get back and works fine.
But for some reason that i dont know and idont udnertand the string that is stored into the database is probably not correctly saved in the correct character encoding, because i always get back NULL when i try to execute the fucntion on smarty:
{$data.custom6|json_decode|var_dump}
So my question is if i have this string, but i dont know how my software save it into the database what should i do to convert it into the correct encodinh and after process it with json_decode ?
Thanks
NOTE 1: i dont know how the backend is saving data into the database and i cnnot influence this step. i can only using a web interface insert my JSON string in the custom field and press a SAVE button –
NOTE 2: sorry for the mistake copying the file here, i placed $json instead $string. But it doesnt work.
Related
When users keep interacting with my web app, the pages keep doing calls so that some info can be stored in a cookie linked file that is stored on the server (with the PHP session file, it gets complex: I don't have choice to see a complete history, etc.)
So, anyway, with every ajax call, I create json_encoded data in a flat file with the unique cookie name.
Data example of one such cookie file: (keys/values may repeat)
{"name":"John Doe"}
{"email":"john#doe.com"}
{"location":"Disneyland, Orlando"}
{"country of residence":"Iceland"}
{"name":"Gill Bates"}
{"email":"Gill.Bates#sicromoft.com"}
Now, when I am searching this file, to retrieve data and to do other stuff, I would like to have the entire contents in one big array as if the entire data ws json_encoded in one shot.
How do I do this? I could do a bunch of str_replace and replace the "{" and "}" and get rid of the carriage returns but that seems to be a bit ugly
Is there a better way?
Thanks
I suggest to fix your json format by using str_replace as you saying because this is the only way to have a valid json format on using this function:
$str = '{"name":"John Doe"}
{"email":"john#doe.com"}
{"location":"Disneyland, Orlando"}
{"country of residence":"Iceland"}
{"name":"Gill Bates"}
{"email":"Gill.Bates#sicromoft.com"}';
$fix_json = "[" . str_replace("}\n{", "},{", $str) . "]";
and after this you can decode you json and convert it with json_decode, like this:
$dataArray = json_decode($fix_json, true);
My API URL Returned code in browser as shown below. but json_decode($api_url,true); returns null.
i checked json_last_error();, it returns 4(json error syntax).
it worked with json_decode(file_get_contents($api_url),true);
why it isn't work with json_decode. please help
{"dataset":{"id":27153572,"dataset_code":"20MICRONS_A_DEBT","database_code":"DEB","name":"20 Microns Limited,Total Debt","description":"\u003cp\u003e20 Microns Limited(NSE:20MICRONS)-Total Debt(Annual)\u003c/p\u003e","refreshed_at":"2018-09-21T08:04:08.278Z","newest_available_date":"2018-03-31","oldest_available_date":"2005-03-31","column_names":["PERIOD","STANDALONE","CONSOLIDATED"],"frequency":"annual","type":"Time Series","premium":true,"limit":null,"transform":null,"column_index":null,"start_date":"2005-03-31","end_date":"2018-03-31","data":[["2018-03-31",128.56,133.68],["2017-03-31",144.9,151.73],["2016-03-31",155.18,163.41],["2015-03-31",152.8,164.62],["2014-03-31",162.01,176.64],["2013-03-31",148.49,164.73],["2012-03-31",144.67,158.6],["2011-03-31",81.42,120.31],["2010-03-31",84.35,87.35],["2009-03-31",58.62,58.62],["2008-03-31",46.52,null],["2007-03-31",42.46,null],["2006-03-31",40.03,null],["2005-03-31",38.98,null]],"collapse":null,"order":null,"database_id":14992}}
What you are trying to do has no sense. $api_url is just an url so when you try to decode it then it doesn't have a json stucture and it will throw an exeption.
What you should decode is the data that this url returns to you.
So First you should get data from url then use json_decode($api_url,true);.
To get data you can use file_get_contents or curl.
Props to u_mulder who hit the nail on the head but I want to break this down for you a little.
Purpose of file_get_contents():
The file_get_contents() function is an inbuilt function in PHP which is used to read the contents of a file into a string.
Please note that the 'file' can be a file residing on your web server or a remote file (URL), which in essence will give you a web document back.
Purpose of json_decode():
The json_decode() function is an inbuilt function in PHP which is used to decode a JSON string. It converts a JSON encoded string into a PHP variable.
With that in mind you can see that performing json_decode on an invalid JSON string or a URL will render your result as NULL.
json_decode('https://www.website.com')
This is essentially what you are doing. performing the file_get_contents inside your json_decode first converts your URL/File ('https://www.website.com') into a string, that string then having JSON is then converted into an array by json_decode.
I try to create a script that decoding a simple JSON string in PHP and I get the following error:
quoted object property name expected
The string I try to decode is the following :
{"values":[{"url":"http://www.google.com","matches":"http|www|google|com"},{"url":"http://www.yahoo.com","matches":"http|www|yahoo|com"}]}
and the code I use to decoded is the following:
json_decode( $json_string );
I also have try to validate my json string in some online json validators, and the string seems to be fine.
Can someone please help me ?
Do you think the problem exists because of the double quotes ?
Update #1
Definetelly was a debuging issue. I place my experience here just to help other devs may come accross the same issue in the feature:
The problem was that my variable that came with the json string was html encoded so instead of the following string :
{"values":[{"url":"http://www.google.com","matches":"http|www|google|com"},{"url":"http://www.yahoo.com","matches":"http|www|yahoo|com"}]}
my variable came with the following string inside :
{"values":[{"url":"http://www.google.com","matches":"http|www|google|com"},{"url":"http://www.yahoo.com","matches":"http|www|yahoo|com"}]}
The mistake by my side was that I used the print_r method instead of the var_dump . This had as a result to print out the " as " in my page .
The json string is valid, and it works. You can add true for the second parameter of json_decode, and you get back an array.
Try the following:
$json_string = '{"values":[{"url":"http://www.google.com","matches":"http|www|google|com"},{"url":"http://www.yahoo.com","matches":"http|www|yahoo|com"}]}';
var_dump(json_decode($json_string, true));
It works for me.
I'm writing PHP code that uses a database. To do so, I use an array as a hash-map.
Every time content is added or removed from my DB, I save it to file.
I'm forced by my DB structure to use this method and can't use mysql or any other standard DB (School project, so structure stays as is).
I built two functions:
function saveDB($db){
$json_db = json_encode($db);
file_put_contents("wordsDB.json", $json_db);
} // saveDB
function loadDB(){
$json_db = file_get_contents("wordsDB.json");
return json_decode($json_db, true);
} // loadDB
When echo-ing the string I get after the encoding or after loading from file, I get a valid json (Tested it on a json viewer) Whenever I try to decode the string using json_decode(), I get null (Tested it with var_dump()).
The json string itself is very long (~200,000 characters, and that's just for testing).
I tried the following:
Replacing single/double-quotes with double/single-quotes (Without any backslashes, with one backslash and three backslashes. And any combination I could think of with a different number of backslashes in the original and replaced string), both manually and using str_replace().
Adding quotes before and after the json string.
Changing the page's encoding.
Decoding without saving to file (Right after encoding).
Checked for slashes and backslashes. None to be found.
Tried addslashes().
Tried using various "Escape String" variants.
json_last_error() doesn't work. I get no error number (Get null, not 0).
It's not my server, so I'm not sure what PHP version is used, and I can't upgrade/downgrade/install anything.
I believe the size has something to do with it, because small strings seem to work fine.
Thanks Everybody :)
In your JSON file change null to "null" and it will solve the problem.
Check if your file is UTF8 encoded. json_decode works with UTF8 encoded data only.
EDIT:
After I saw uploaded JSON data, I did some digging and found that there are 'null' key. Search for:
"exceeding":{"S01E01.html":{"2217":1}},null:{"S01E01.html":
Change that null to be valid property name and json_decode will do the job.
I had a similar problem last week. my json was valid according to jsonlint.com.
My json string contained a # and a & and those two made json_decode fail and return null.
by using var_dump(json_decode($myvar)) which stops right where it fails I managed to figure out where the problem was coming from.
I suggest var_dumping and using find dunction to look for these king of characters.
Just on the off chance.. and more for anyone hitting this thread rather than the OP's issue...I missed the following, someone had htmlentities($json) way above me in the call stack. Just ensure you haven't been bitten by the same and check the html source.
Kickself #124
I have the following JSON formatted string:
{
"hooks":[
{
"type":"subscribe",
"id":1331741592.6925,
"email":"JoeX#test-email.com",
"status":"Active",
"custom_fields":"{\"first_name\":\"Joe\",\"last_name\":\"X\"}",
"ip_created":"24.199.200.142",
"list_id":"33",
"list_type":"internal",
"list_name":"Administrator List 2",
"list_optin":false
},
{
"type":"subscribe",
"id":1331741592.7067,
"email":"JaneY#test-email.com",
"status":"Active",
"custom_fields":"{\"first_name\": \"Jane\",\"last_name\":\"Y\"}",
"ip_created":"24.199.200.142",
"list_id":"33",
"list_type":"internal",
"list_name":"Administrator List 2",
"list_optin":false
}
]
}
I want to use the PHP json_decode() function to put it in an associative array.
When I do run the script, debugging shows the value of the new array as null, so I presume the decode is failing. We aren't running PHP 5.3, so I can't use json_last_error(). Here is the code:
$hooks = (the JSON string from above);
$hooksArray = json_decode($hooks, true);
Any ideas why the $hooksArray is coming back null?
Is the JSON string inside your PHP source? Perhaps it's not interpreting the escaped backslashes correctly.
I tried the following experiment in Python for reference: Dumped the JSON data into a multi-line string via the REPL and decode it with json.loads(). It choked on the in-string quotes in the first instance of the custom_fields string. When I examined the multi-line string, all the escapes were gone, leaving me only with the quotes.
When I put the same JSON data in an external file and loaded it, it worked fine.
I put the JSON data in an external file and replaced all '\"' instances with '\\"' and then the first experiment started to work.
Maybe that will work for you too.