JSON Not Working on PHP Script - php

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.

Related

Get value from nested json php

I am receiving data from a webhook with the following code below.
<?php
$inputJSON = file_get_contents('php://input');
$input = json_decode($inputJSON, TRUE);
$myfile = fopen("callback.txt", "a") or die("Unable to open file!");
$txt = $input["payload"]["type"];
fwrite($myfile, "\n". $txt);
fclose($myfile);
http_response_code(200);
?>
I am trying to get the 'type' value from the retuned output. I have found that using an if statement inside a for each loop would do the job. However i'm sure this isn't an ideal solution. is there a more direct way of getting that element?
The code above is outputting an empty text file.
and the documentation shows the json should be in the following format:
{
"action": "add",
"collection": "broadcast",
"payload": {
"author": "Sveninge Bambuser",
"created": 1474033783,
"customData": "",
"height": 540,
"id": "9353eaec-794f-11e6-97c0-f19001529702",
"ingestChannel": "cfc8626c-9a0e-ab78-6424-3eb0978d8e45",
"lat": 63.205312,
"length": 0,
"lon": 17.13011,
"positionAccuracy": 25,
"positionType": "GPS",
"preview": "https://archive.bambuser.com/9353eaec-794f-11e6-97c0-f19001529702.jpg",
"resourceUri": "https://cdn.bambuser.net/broadcasts/9353eaec-794f-11e6-97c0-f19001529702?da_signature_method=HMAC-SHA256&da_id=9353eaec-794f-11e6-97c0-f19001529702&da_timestamp=1474033783&da_static=1&da_ttl=0&da_signature=eaf4c9cb29c58b910dcbad17cf7d8a3afa4e6a963624ba4c4fd0bb5bade1cdd6",
"tags": [
{
"text": "whoa"
}
],
"title": "Amazing!",
"type": "live",
"width": 960
},
"eventId": "93df93061a891c23"
}
I replaced:
$txt = $input["payload"]["type"];
with:
$txt = $input['payload']['type'];
it appears to be the double quotes causing the issue.

Getting data from json and passing to url

Want to send the json data to my url, when the json is received i receive all the json data on the url and not the data from 'resolvedQuery'
$update_response = file_get_contents("php://input");
$update = json_decode($update_response, true);
$results = $update['result']['resolvedQuery'];
$url = "https://autoremotejoaomgcd.appspot.com/sendmessage?key=APA91bEq&message=Data" . urlencode(json_encode($update));
Json Data
{
"id": "4ed272a3-b9a4-4f18-a67e-10e12e4f4149",
"timestamp": "2017-12-10T10:07:54.282Z",
"lang": "en",
"result": {
"source": "agent",
"resolvedQuery": "turn livingroom light on",
"action": "",
"actionIncomplete": false,
"parameters": {
"power-toggle": "on",
"room": "livingroom"
},
"contexts": [],
"metadata": {
"intentId": "19764ecc-715c-4b25-960f-9845f2aef1f9",
"webhookUsed": "true",
"webhookForSlotFillingUsed": "false",
"webhookResponseTime": 503,
"intentName": "lights"
},
"fulfillment": {
"speech": "Ok, Turning livingroom light on",
"messages": [
{
"type": 0,
"speech": "Ok, Turning livingroom light on"
}
]
},
"score": 1
},
"status": {
"code": 206,
"errorType": "partial_content",
"errorDetails": "Webhook call failed. Error: Webhook response was empty.",
"webhookTimedOut": false
},
"sessionId": "395d3517-05da-42ac-9037-dadac519ab0b"
}
How do i get data from 'resolvedQuery' and send it to my URL
In the code you provided, you have the following line of code
$url = "https://autoremotejoaomgcd.appspot.com/sendmessage?key=APA91bEq&message=Data"
. urlencode(json_encode($update));
You are appending to the URL parameter message the results of json_decode($update_response, true). $update_response contains all the decoded JSON data posted by the HTTP request which is not what you want.
I believe what you want is a new parameter called resolved-query to be set to the results of json_decode($result, true).
Try chaninging your $url variable to the following:
$url = "https://autoremotejoaomgcd.appspot.com/sendmessage?key=APA91bEq&message=Data&resolved-query="
. urlencode(json_encode($result));
URL will be set to the following string:
https://autoremotejoaomgcd.appspot.com/sendmessage?
key=APA91bEq&
message=Data&
resolved-query=turn+livingroom+light+on

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

Preserving original value of string and decode it like a json

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

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