Preserving original value of string and decode it like a json - php

I want preserve original value of target field and use json_decode to use following string as object:
{
"translatorID": "f4a5876a-3e53-40e2-9032-d99a30d7a6fc",
"label": "ACL",
"creator": "Nathan Schneider",
"target": "^https?://(www[.])?aclweb\\.org/anthology-new/[^#]+",
"minVersion": "1.0.7",
"maxVersion": "",
"priority": 100,
"browserSupport": "gcs",
"inRepository": true,
"translatorType": 4,
"lastUpdated": "2012-01-01 01:42:16"
}

What you can do before parsing with json_decode is:
$string = str_replace('\\', '\\\\\\\\', $string);
var_dump(json_decode($string, true));
This must be a bug in the json parser.
The method is not very clean but at least you're getting your results.

Did you try stripping the slashes off?
This worked for me :
$string = '{
"translatorID": "f4a5876a-3e53-40e2-9032-d99a30d7a6fc",
"label": "ACL",
"creator": "Nathan Schneider",
"target": "^https?://(www[.])?aclweb\.org/anthology-new/[^#]+",
"minVersion": "1.0.7",
"maxVersion": "",
"priority": 100,
"browserSupport": "gcs",
"inRepository": true,
"translatorType": 4,
"lastUpdated": "2012-01-01 01:42:16"
}';
var_dump( json_decode(stripslashes ($string)));

Related

How to put an API return string into an array

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

json_decode doesn't work on my string

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);

JSON Not Working on PHP Script

I got 2 JSON files extracted from the same db,
a:)
{
"hint_data": {
"locations": ["AXQDAP____8AAAAABwAAABEAAAAYAAAAIwIAAERwAgAAAAAADgyCAef7TAMCAAEB", "bOsDAP____8AAAAAAwAAAAcAAADFAQAAFAAAAEJwAgAAAAAANQeCAdzdTAMFAAEB"],
"checksum": 326195011
},
"route_name": ["", ""],
"via_indices": [0, 15],
"via_points": [
[25.299982, 55.376873],
[25.29874, 55.369179]
],
"found_alternative": false,
"route_summary": {
"end_point": "",
"start_point": "",
"total_time": 101,
"total_distance": 871
},
"route_geometry": "{_ego#m}|rhBpBaBvHuC`EuArEUtEtAlDvEnD`MlDvMli#hsEfFzn#QlTgNhwCs#fKwBjF",
"status_message": "Found route between points",
"status": 0
}
b:)
{
"alternative_names": [
["", ""]
],
"route_name": ["", ""],
"status_message": "Found route between points",
"route_geometry": "qo{o#wpslhBmFZwEpBgDzDeBlFWdGv#GCzEyBfIyEtEoNtEuMpAuHkAsCgC[mB{AgCuA{#uCa#}Cl#yBtB}#lDVhEcAtDmCdBcDx#iDDeDk#uBeBeB_CcGcXyFi^{Dg\\wBkP_Fs^wBiS_Ce[_D}UwAcKiBqIgI_TeLaUcMmP_IsHqf#_WyJeE}FMkDjIiTth#y|#loBq^vy#mu#fw#cUxOco#r^gb#zRoOjPsBfMq#rMjBdPnEpKlEnHJ~Dvn#la#nd#pT|f#lLv_#pRzLbHnb#fUxc#lMnaC~zAncBxnAkB|bB|CbmCl]rYxCzkCjwBzoBjxGl_G|fNhcMf~E~mE~pFt}EjbBlzAhvInyHfqDb~CblAw#poAzt#z}#bb#diD~dBxtEjgCfjDljBpuAfw#bpGngDhqF~yC~g#la#v~#ni#rbAjg#jPJlCFNdDGdDu#j#eAhBa#lCLdCaCjI_BtCy#vA_DvF}qAf}Bof#l{#{CnFoKdR}mAxBgM|TkJxPmLlSsf#|}#gf#x#kOzXmEfGmSx^kf#tw#mDtL}k#r~#ykCjjEau#niAee#bu#uUl\\}DpFzCrCr|#dt#|NbLroBx_BdZlV|DbDpBr~Anq#xm#r|#ls#|y#dq#}OXuMQcDhEoBgBeCCu[xXmBH",
"route_summary": {
"end_point": "",
"start_point": "",
"total_time": 824,
"total_distance": 15391
},
"found_alternative": true,
"alternative_summaries": [{
"end_point": "",
"start_point": "",
"total_time": 886,
"total_distance": 14967
}],
"via_points": [
[25.196808, 55.273754],
[25.139168, 55.187702]
],
"status": 0,
"via_indices": [0, 144],
"hint_data": {
"locations": ["TdMLAP____8AAAAADwAAAA8AAAA9AAAAbAAAAOtwBgAAAAAACXmAARxpSwMEAAEB", "4Q4AAGKyBgAAAAAACQAAAAAAAAAhAQAAAAAAAGUYAAAAAAAA4Zd_AfgYSgMGAAEB"],
"checksum": 326195011
},
"alternative_geometries": ["qo{o#wpslhBmFZwEpBgDzDeBlFWdGv#GCzEyBfIyEtEoNtEuMpAuHkAsCgC[mB{AgCuA{#uCa#}Cl#yBtB}#lDVhEcAtDmCdBcDx#iDDeDk#uBeBeB_CcGcXyFi^{Dg\\wBkP_Fs^wBiS_Ce[_D}UwAcKiBqIgI_TeLaUcMmP_IsHqf#_WyJeE}FMkDjIiTth#y|#loBq^vy#ec#vfAyeAfcCok#vtA}Wtx#uS|d#skAvfCgExJgJpTqH|O}#n~#wSve#qEhKkYdp#gB~DuUrk#_JdRsAhDmJlVqd#rcAuM|Zeg#zkAiKzUgIbS}B~EtDvBhr#a#dQ~J|rBpmAj_CfyAlAzD^lDgHnOyQlg#w[l|#}Q~d#eBB}Af#mAdAw#bBWpBJrBn#hBaAjGif#ptAk^rmAoVxy#cHjPmCHE|Bp[xRpc#ZfLvIzLlIreG~cEjrArz#rmAl|#lbDrzBjWlQ|xA~bAho#pc#d_#jWng#j^hNzJvGnEnPjLlAx#lgAhv#bGvCjkBvoAbjDr}BvfAx{#t\\rSfoDviC~zAjgAfOxIvAbAjwCtsBv|#|m#bD|BvLId_Dt|BtLlIxsAx_AfE~Crn#hc#rKvIh_BniApe#z\xIpGtoBpxAtEdDrQrMzjChlB~#lo#nwFpE|jBl|AzFzE|DfDvDrCjKfJr#n\\pLzKnBzzAdO~LhaFxaEzCdCnLpKbp#ti#nIjHdRzMjo#tg#~MvKpwCtdClw#bm#z[bWfr#vk#zCrCr|#dt#|NbLroBx_BdZlV|DbDpBr~Anq#xm#r|#ls#|y#dq#}OXuM`QcDhEoBgBeCCu[xXmBH"],
"alternative_indices": [0, 183]
}
And I am running this script on every JSON file.
Here is the script.
<?php
$json = '{"hint_data":{"locations":["AXQDAP____8AAAAABwAAABEAAAAYAAAAIwIAAERwAgAAAAAADgyCAef7TAMCAAEB","bOsDAP____8AAAAAAwAAAAcAAADFAQAAFAAAAEJwAgAAAAAANQeCAdzdTAMFAAEB"],"checksum":326195011},"route_name":["",""],"via_indices":[0,15],"via_points":[[25.299982,55.376873],[25.29874,55.369179]],"found_alternative":false,"route_summary":{"end_point":"","start_point":"","total_time":101,"total_distance":871},"route_geometry":"{_ego#m}|rhBpBaBvHuC`EuArEUtEtAlDvEnD`MlDvMli#hsEfFzn#QlTgNhwCs#fKwBjF","status_message":"Found route between points","status":0}';
$data = json_decode($json);
$totalTime = $data->route_summary->total_time;
var_dump($totalTime); // DUMPS 101
I am getting the first JSON file output correctly but I am getting an error in the 2nd one.
Please tell me what's wrong with the JSON file.
Your json is not valid.
The "alternative_geometries" property contains a string that is not properly encoded. (\x is not valid. If you want the slash, then it would need to be \\x)
Try validating it somewhere like this: http://jsonlint.com/
1) put data to text file
2) try again with:
<?php
$data = file_get_contents('./relative/path/to/file.json');
$data = json_decode($data);
$totalTime = $data->route_summary->total_time;
var_dump($totalTime);
it would be better to write data to files and put somewhere to download them to check the file.

Json Object to PHP array - not converting

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

decoding stripe json with json_decode not working

I have json from stripe and I am trying to decode it json_decode.
I am not getting an error. Just nothing is returning. I am getting the data back from stripe, I just cant decode it.
{
"created":1326853478,
"data":{
"object":{
"amount":4500,
"card":{
"country":"US",
"cvc_check":"pass",
"exp_month":7,
"exp_year":2014,
"fingerprint":"9aQtfsI8a17zjEZd",
"id":"cc_00000000000000",
"last4":"9782",
"object":"card",
"type":"Visa"
},
"created":1322700852,
"currency":"usd",
"disputed":false,
"fee":0,
"id":"ch_00000000000000",
"livemode":false,
"object":"charge",
"paid":true,
"refunded":true
}
},
"id":"evt_00000000000000",
"livemode":false,
"type":"charge.refunded"
}
// retrieve the request's body and parse it as JSON
$body = #file_get_contents('php://input');
$event_json = json_decode($body,true);
print_r($event_json);
Any ideas?
The php://input stream allows you to read raw data from the request body. This data will be a string and depending on what sort of values are in the request, will look something like:
"name=ok&submit=submit"
This is not JSON and therefore won't decode as JSON the way you expect.The json_decode() function returns null if it can't be decoded.
Where are you getting the JSON you posted above? That is the value you need to pass into json_decode().
If JSON is being passed in the request, like in the instance of callbacks, you would still need to parse that portion out to get just the JSON. If the php://input stream gives you name=ok&submit=submit&json={"created": 1326853478} then you'd have to parse it out. You can use this function from the PHP manual to seperate the values to work like the $_POST array:
<?php
// Function to fix up PHP's messing up POST input containing dots, etc.
function getRealPOST() {
$pairs = explode("&", file_get_contents("php://input"));
$vars = array();
foreach ($pairs as $pair) {
$nv = explode("=", $pair);
$name = urldecode($nv[0]);
$value = urldecode($nv[1]);
$vars[$name] = $value;
}
return $vars;
}
?>
To use it:
$post = getRealPOST();
$stripe_json = $post['json'];
$event_json = json_decode($stripe_json);
Here, I ran this:
<?php
$data = '{ "created": 1326853478, "data": { "object": { "amount": 4500, "card": { "country": "US", "cvc_check": "pass", "exp_month": 7, "exp_year": 2014, "fingerprint": "9aQtfsI8a17zjEZd", "id": "cc_00000000000000", "last4": "9782", "object": "card", "type": "Visa" }, "created": 1322700852, "currency": "usd", "disputed": false, "fee": 0, "id": "ch_00000000000000", "livemode": false, "object": "charge", "paid": true, "refunded": true } }, "id": "evt_00000000000000", "livemode": false, "type": "charge.refunded" }';
$arr = json_decode($data, true);
print_r($arr);
?>
And it worked. So, theoretically you should be able to use:
<?php
$arr = json_decode(file_get_contents('php://input'), true);
print_r($arr);
?>
As Ignacio Vazquez-Abrams said, don't use the '#' character because it obscures error messages and makes it harder to debug.
I would also check what version of PHP you have. json_decode() is only available on version 5.2.0 and later.

Categories