Writing JSON object to .json file on server - php

I'm trying to write my JSON object to a .json file on the server. The way I'm doing this now is:
JavaScript:
function createJsonFile() {
var jsonObject = {
"metros" : [],
"routes" : []
};
// write cities to JSON Object
for ( var index = 0; index < graph.getVerticies().length; index++) {
jsonObject.metros[index] = JSON.stringify(graph.getVertex(index).getData());
}
// write routes to JSON Object
for ( var index = 0; index < graph.getEdges().length; index++) {
jsonObject.routes[index] = JSON.stringify(graph.getEdge(index));
}
// some jQuery to write to file
$.ajax({
type : "POST",
url : "json.php",
dataType : 'json',
data : {
json : jsonObject
}
});
};
PHP:
<?php
$json = $_POST['json'];
$info = json_encode($json);
$file = fopen('new_map_data.json','w+');
fwrite($file, $info);
fclose($file);
?>
It is writing fine and the information seems to be correct, but it is not rendering properly. It is coming out as:
{"metros":["{\\\"code\\\":\\\"SCL\\\",\\\"name\\\":\\\"Santiago\\\",\\\"country\\\":\\\"CL\\\",\\\"continent\\\":\\\"South America\\\",\\\"timezone\\\":-4,\\\"coordinates\\\":{\\\"S\\\":33,\\\"W\\\":71},\\\"population\\\":6000000,\\\"region\\\":1}",
... but I'm expecting this:
"metros" : [
{
"code" : "SCL" ,
"name" : "Santiago" ,
"country" : "CL" ,
"continent" : "South America" ,
"timezone" : -4 ,
"coordinates" : {"S" : 33, "W" : 71} ,
"population" : 6000000 ,
"region" : 1
} ,
Why am I getting all of these slashes and why it is all on one line?

You are double-encoding. There is no need to encode in JS and PHP, just do it on one side, and just do it once.
// step 1: build data structure
var data = {
metros: graph.getVerticies(),
routes: graph.getEdges()
}
// step 2: convert data structure to JSON
$.ajax({
type : "POST",
url : "json.php",
data : {
json : JSON.stringify(data)
}
});
Note that the dataType parameter denotes the expected response type, not the the type you send the data as. Post requests will be sent as application/x-www-form-urlencoded by default.
I don't think you need that parameter at all. You could trim that down to:
$.post("json.php", {json : JSON.stringify(data)});
Then (in PHP) do:
<?php
$json = $_POST['json'];
/* sanity check */
if (json_decode($json) != null)
{
$file = fopen('new_map_data.json','w+');
fwrite($file, $json);
fclose($file);
}
else
{
// user has posted invalid JSON, handle the error
}
?>

Don't JSON.stringify. You get a double JSON encoding by doing that.
You first convert your array elements to a JSON string, then you add them to your full object, and then you encode your big object, but when encoding the elements already encoded are treated as simple strings so all the special chars are escaped. You need to have one big object and encode it just once. The encoder will take care of the children.
For the on row problem try sending a JSON data type header: Content-type: text/json I think (didn't google for it). But rendering will depend only on your browser. Also it may be possible to encode with indentation.

Probably too late to answer the question. But I encountered the same issue. I resolved it by using "JSON_PRETTY_PRINT"
Following is my code:
<?php
if(isset($_POST['object'])) {
$json = json_encode($_POST['object'],JSON_PRETTY_PRINT);
$fp = fopen('results.json', 'w');
fwrite($fp, $json);
fclose($fp);
} else {
echo "Object Not Received";
}
?>

<html>
<head>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<script type="text/javascript" src="http://code.jquery.com/jquery-1.4.3.min.js" ></script>
</head>
<body>
<?php
$str = file_get_contents('data.json');//get contents of your json file and store it in a string
$arr = json_decode($str, true);//decode it
$arrne['name'] = "sadaadad";
$arrne['password'] = "sadaadad";
$arrne['nickname'] = "sadaadad";
array_push( $arr['employees'], $arrne);//push contents to ur decoded array i.e $arr
$str = json_encode($arr);
//now send evrything to ur data.json file using folowing code
if (json_decode($str) != null)
{
$file = fopen('data.json','w');
fwrite($file, $str);
fclose($file);
}
else
{
// invalid JSON, handle the error
}
?>
<form method=>
</body>
data.json
{
"employees":[
{
"email":"11BD1A05G9",
"password":"INTRODUCTION TO ANALYTICS",
"nickname":4
},
{
"email":"Betty",
"password":"Layers",
"nickname":4
},
{
"email":"Carl",
"password":"Louis",
"nickname":4
},
{
"name":"sadaadad",
"password":"sadaadad",
"nickname":"sadaadad"
},
{
"name":"sadaadad",
"password":"sadaadad",
"nickname":"sadaadad"
},
{
"name":"sadaadad",
"password":"sadaadad",
"nickname":"sadaadad"
}
]
}

Related

Saving data across multiple lines JSON

Currently I have PHP and JS save my data in a JSON.
Below is the code for it:
PHP:
<?php
$jsonString = file_get_contents('passwords.json');
$data = json_decode($jsonString, true);
// get the q parameter from URL
$q = $_REQUEST["q"];
$item = $_REQUEST["item"];
// or if you want to change all entries with activity_code "1"
foreach ($data["passwords"] as $key => $password) {
echo $data["passwords"][$key]['timesToUse'] - 1;
if ($password['password'] == $q) {
$data["passwords"][$key]['timesToUse'] = $data["passwords"][$key]['timesToUse'] - 1;
$data["passwords"][$key]['winningItem'] = $item;
}
}
$newJsonString = json_encode($data);
file_put_contents('passwords.json', $newJsonString);
?>
JS:
var xmlhttp = new XMLHttpRequest();
xmlhttp.open("GET", "passwords.php?q="+passwords[i].password+"&item="+winningItem.getFullName(), true);
xmlhttp.send();
The issue that I am having is that initially my JSON file looks like this:
{"password":"IS360H","timesToUse":1,"winningItem":""},
{"password":"AGRD33","timesToUse":1,"winningItem":""},
{"password":"4BX0FV","timesToUse":1,"winningItem":""},
{"password":"99NOTX","timesToUse":1,"winningItem":""},
{"password":"X2Z8BO","timesToUse":1,"winningItem":""},
{"password":"R9G4Q0","timesToUse":1,"winningItem":""},
{"password":"CG9RGT","timesToUse":1,"winningItem":""},
As you can see it is nice and neat and is sitting at 1 password per line. However once the file gets modified, it turns to this:
{"password":"IS360H","timesToUse":0,"winningItem":"counterUAV"},{"password":"AGRD33","timesToUse":0,"winningItem":"sentryGun"},"password":"4BX0FV","timesToUse":0,"winningItem":"chopperGunner"},"password":"99NOTX","timesToUse":1,"winningItem":""},{"password":"X2Z8BO","timesToUse":1,"winningItem":""}, {"password":"R9G4Q0","timesToUse":1,"winningItem":""},"password":"CG9RGT","timesToUse":1,"winningItem":""},
What do I need to do to make my JSON file preserve the line breaks?
Thank you!
There is option JSON_PRETTY_PRINT available in json_encode function, if you are using same for encoding json. Try following:
$json_string = json_encode($data, JSON_PRETTY_PRINT);
Read more about json_encode

Nested dictionary skips inner content while sent to a PHP webserver as JSON using Python 3.0 (Requests)

I have a large python dictionary, which is sent out as a JSON in a POST request using the py requests library to a web service which accepts incoming JSONs (XAMPP/PHP set up in localhost).
When I receive the transmitted JSON data through the POST request, PHP always gives the output as array, and not as a serialized JSON string.
Secondly, nested elements are missing from the data captured on PHP end.
I am using the following snip to do the job.
Python code :
import json
import requests
dummy_data = {
"param1": "ABCDEF",
"param2": {
"0": "inner_data_0",
"1": "inner_data_1"
},
"param3": {
"very_big_text_key_1": {
"inner_key_1": "inner_value_1",
"inner_key_2": ["very_large_string_item_as_inner_value_2"],
"inner_key_3": "inner_value_3"
},
"very_big_text_key_2": {
"inner_key_1": "inner_value_1",
"inner_key_2": ["very_large_string_item_as_inner_value_2"],
"inner_key_3": "inner_value_3"
}
}
}
headers = {'Content-Type': 'application/json', 'accept' : 'application/json'}
r = requests.post("http://localhost/test/data.php", params = (dummy_data), headers = headers)
print (r.text)
Also tried with :
headers = {'Content-Type': 'application/json'}
Both give the same output as below:
*Hello World!<br/>Printing GET array ...<br/>array(4) {
["param1"]=>
string(6) "ABCDEF"
["param2"]=>
string(1) "1"
["param3"]=>
string(19) "very_big_text_key_2"
["param4"]=>
string(6) "GHIJKL"
}
<br/>Printing POST array ...<br/>array(0) {
}*
I used json and data as parameters to "requests".
r = requests.post("http://localhost/test/data.php", json = (dummy_data), headers = headers)
and
r = requests.post("http://localhost/test/data.php", data = (dummy_data), headers = headers)
Output is as below :
*Hello World!<br/>Printing GET array ...<br/>array(0) {
}
<br/>Printing POST array ...<br/>array(0) {
}*
I am accepting data as follows in PHP code:
<?php
print "Hello World!";
echo "<br/>";
print "Printing GET array ...";
echo "<br/>";
var_dump($_GET);
echo "<br/>";
print "Printing POST array ...";
echo "<br/>";
var_dump($_POST);
?>
The inner text doesn't seem to be appearing in any of the scenarios. I have tried to implement some solutions as suggested by members of stackoverflow. But still i am facing the above mentioned issue.
The problem is now resolved. The resolution happend after consideration of the following points:
JSON passed by Python is not de-serialized by default, by PHP and has to be serialized, after inspection of "Content-type" header.
Once de-serialized, the passed JSON content was then used for further processing.
Hence the key to solve the problem was, to check the content-length, and content-type headers. If content-length was found greater than 0 and content type was application/json, the incoming JSON can be de-serialized using json_decode().
The code snips for PHP and Python, using which the following was accomplished is as below:
On the Python side:
import json
import requests
dummy_data = {
"param1": "ABCDEF",
"param2": {
"0": "inner_data_0",
"1": "inner_data_1"
},
"param3": {
"very_big_text_key_1": {
"inner_key_1": "inner_value_1",
"inner_key_2": ["very_large_string_item_as_inner_value_2"],
"inner_key_3": "inner_value_3"
},
"very_big_text_key_2": {
"inner_key_1": "inner_value_1",
"inner_key_2": ["very_large_string_item_as_inner_value_2"],
"inner_key_3": "inner_value_3"
}
}
}
headers = {'Content-Type': 'application/json'}
r = requests.post("http://localhost/test/data.php", data = json.dumps(dummy_data), headers=headers)
print (r.text)
On the PHP side:
...
if(#$_SERVER["CONTENT_LENGTH"] > 0){
$contentType = $_SERVER["CONTENT_TYPE"];
if($contentType == "application/json"){
$decoded_data = json_decode(file_get_contents("php://input"), true);
}
else{
echo "Incoming data is not a JSON!";
}
return $decoded_data;
}

API Data Return to HTML

I have added new data to my API. I want to return it as plain text
This is the API response PHP returns.
{
"apiVersion":"1.0",
"data":{
"location":"London",:
{
"pressure":"1021",
"temperature":"23",
"skytext":"Sky is Clear",
"humidity":"40",
"wind":"18.36 km/h",
"date":"07-10-2015",
"day":"Friday"
}
}
I want to return the pressure value on my html page so my users can see the reading. I am having issues displaying it.
This is my PHP api.php
require_once('./includes/config.php');
require_once('./includes/functions.php');
error_reporting(0);
header('Content-Type: text/plain; charset=utf-8;');
$city = $_GET['city'];
if(isset($city)) {
$weather = new Weather($conf['apikey'], $_GET['f']);
$weather_current = $weather->get($city, 0, 0, null, null);
$now = $weather->data(0, $weather_current);
if($now['location'] !== NULL) {
echo '{"apiVersion":"1.0", "data":{ "location":"'.$now['location'].'", "temperature":"'.$now['temperature'].'", "pressure":"'.$now['pressure'].'", "skytext":"'.$now['description'].'", "humidity":"'.$now['humidity'].'", "wind":"'.$now['windspeed'].'", "date":"'.$now['date'].'", "day":"'.$now['day'].'" } }';
} else {
echo '{"apiVersion":"1.0", "data":{ "error":"The \'city\' requested is not available, make sure it\'s a valid city." } }';
}
} else {
echo '{"apiVersion":"1.0", "data":{ "error":"You need to specify the city parameter" } }';
}
In order to fetch data from a JSON source you should parse the data with the json_decode() method. You can then use the second parameter to parse it into an array. If you omit the second parameter you would get an array of objects.
Important: It seems your JSON has a syntax error too. I have added a weather key before the weather information.
$data = '{
"apiVersion":"1.0",
"data":{
"location":"London",
"weather":{ // Notice the new key!
"pressure":"1021",
"temperature":"23",
"skytext":"Sky is Clear",
"humidity":"40",
"wind":"18.36 km/h",
"date":"07-10-2015",
"day":"Friday"
}
}
}';
$json = json_decode($data, true);
You should then be able to fetch the pressure as an associative array.
$pressure = $json['data']['weather']['pressure']; // Equals: 1021
Hope this can help you, happy coding!
First of all, you need to validate your JSON. It is missing some key things that will keep you from being able to parse it. Use JSONLint to verify your JSON.
After modification the JSON to make it valid I did the following:
$json = '{"apiVersion":"1.0", "data":{ "location":"London", "data":{ "pressure":"1021", "temperature":"23", "skytext":"Sky is Clear", "humidity":"40", "wind":"18.36 km/h", "date":"07-10-2015", "day":"Friday" }}}';
$obj_style = json_decode($json);
$array_style = json_decode($json, true);
echo $obj_style->data->data->pressure;
echo $array_style['data']['data']['pressure'];
Using json_decode() I was able to setup a way to parse the JSON two ways, once as an object and once as an array (adding the true flag returns the results as an array).
From there all you have to do is drill town to the bits of information that you want to display.

Parsererror when Using Jquery Ajax To Get MYSQL Data From PHP

JQuery
function save() {
imageData = $(".sigPad").signaturePad().getSignatureImage();
consumeData = $('#consume').val();
$.ajax({
type: "POST",
url: "",
data: {'signatureasimage' : imageData, 'consume' : consumeData },
dataType: 'json',
cache: false,
success: function(response){
alert(response.msg);
/*var imageUrl = response['signature_image'];
d = new Date();
$(".signatureImage").attr("src",imageUrl);
if (response.status == true) {
window.location.href = "<?php echo ROOT_URL.'esignup/attendees_list.php?icode='.$icode;?>";
}*/
},
error: function(x,e){
if(x.status==0){
alert('You are offline!!\n Please Check Your Network.');
}else if(x.status==404){
alert('Requested URL not found.');
}else if(x.status==500){
alert('Internel Server Error.');
}else if(e=='parsererror'){
alert('Error.\nParsing JSON Request failed.');
}else if(e=='timeout'){
alert('Request Time out.');
}else {
alert('Unknow Error.\n'+x.responseText);
}
}
});
};
PHP
$data = array();
$confirmationData = array();
$data['attendee_id'] = $attendeeId;
$data['is_consume_the_provided_meal'] = $_POST['consume'];
$data['signature_image'] = $destination;
$data['confirmed'] = 1;
if($confirmedAttendee){
$sql = "SELECT * FROM `".TBL_ATTENDEE_CONFIRMATION."` WHERE `attendee_id` = '.$attendeeId.'";
$confirmationData = selectFrom($sql);
update_array('tbl_attendee_confirmation', $data, array('attendee_id' => $attendeeId));
$confirmationData = selectFrom($sql);
}else{
var_dump("it went through insert array");
insert_array('tbl_attendee_confirmation', $data);
}
$data = array();
$data['msg']="Testing, testing.";
echo json_encode($data);
Jquery ajax does post request with data imageData and consumeData. imageData and consumeData are strings. Copying to file works and the data updates the table. The problem is I get parsererror when I want to get imageUrl so I can update the sigImage with the new image source. I commented the part where I replace the image src with new imageURL. Does anyone know the issue?
Error shows up as "alert('Error.\nParsing JSON Request failed.');" from code. Error still shows up with test code.
Try doing this in your PHP:
echo json_encode($data, JSON_FORCE_OBJECT);
I don't completely understand it, but in my experience if you are returning an array you've built in PHP to be parsed using the ECMAScript JSON object, you need to use the JSON_FORCE_OBJECT constant to ensure that it returns a JSON object instead of a JSON array.
json_encode constants
You also could try outputting the header for JSON before echoing your JSON encoded array, gimme a sec.
header('Content-Type: application/json');
Also here

php json format

I have a json response in this url, which I have to validate from this site.
I have stuck my head through many solutions,and I don't know what's wrong here.
I am very thankful for any help suggestions.
this is the code
header('Content-type: application/json');
$obj=array();
$UID=isset($_REQUEST['UID'])?$_REQUEST['UID']:'';
if($UID!='')
{
$sound_cloud=getLatestSound($UID);
if($sound_cloud==false)
{
$sound_cloud['status']="No Record Found";
$obj['status']="No Record Found";
}
else
{
$sound_cloud['status']="successfull";
}
}
else
{
$sound_cloud['errors']="required UID";
}
print stripslashes(json_encode($sound_cloud));
exit;
<?php
$json = '{"stream_url":"http://api.soundcloud.com/tracks/74950626/stream?client_id=b45b1aa10f1ac2941910a7f0d10f8e28","title":"Klaypex-Jump","status":"successfull"}';
$arrayval = json_decode($json);
print_r($arrayval);
// OR
$url = 'http://knowyourdj.staging.techliance.com/webservices?action=GetSoundCloud&UID=1';
$json = file_get_contents($url);
$arrayval = json_decode($json);
print_r($arrayval);
?>
Result:
stdClass Object ( [stream_url] => http://api.soundcloud.com/tracks/74950626/stream?client_id=b45b1aa10f1ac2941910a7f0d10f8e28 [title] => Klaypex-Jump [status] => successfull )
use
$json = file_get_contents('http://knowyourdj.staging.techliance.com/webservices?action=GetSoundCloud&UID=1');//fetch contents from server
$json = json_decode($json); // parse fetched contents
if(!empty($josn)){
print_r($json);
}else{
echo 'no result were found';
}
//lets find what we had parse
echo it, not print. just try~
print stripslashes(json_encode($sound_cloud));
=>
echo stripslashes(json_encode($sound_cloud));
------------------ edit
If this isn't a solution, I think this is a kind of same origin policy problem.
double check your url, it should have same domain with web page server.
refrence - same origin policy
use jquery jsonp,
You can make an ajax call with jquery to your php like this
$.ajax({
type:"POST",
url:'/example.php', //your url
data:{'seguros':a, 'esp':esp,'cont':cont}, //your variables
success: function(data){
//handle your answer here
}
});

Categories