I'm using typescript and I'm trying to declare a variable with the data from my json file. I already made some interfaces using js2ts.com. But I don't know how to call the json file in my typescript file.
If it's just a json file/structure, you're going to need to make an AJAX call to it like it was a server resource. If it's an object within a module/library, you can import the object. I'm assuming this is a web app, since you mentioned ionic. If it were a NodeJS app, you could load the resource using the fs module.
Some flavor of the following should work:
$http({
method: 'GET',
url: '/PATH_TO_JSON'
}).then(function success(response) {
// Success handling
}, function failure(response) {
// Error handling
});
If you are attempting to access the file when it is on the device, look into the Cordova File API.
Related
I am trying to send to my flask app json data and having it return a CSV file. My ajax request is sending JSON data to the view via POST request and then the view is supposed to return back a csv file. However, it fails to return the csv file in the browser as a download. I'm not sure how to make it work or if its even possible. Thanks!
// AJAX - Send data over to python and return csv
$("#export").click(
function(){
$.ajax({
url: "/dbCSV",
type: "POST",
contentType: 'application/json;charset=UTF-8',
dataType:"json",
data: JSON.stringify(datam)
});
event.preventDefault();
}
);
#analyzers.route("/dbCSV", methods=["GET","POST"])
def dbCSV():
if request.method=="POST":
data = pd.DataFrame(request.get_json())
resp = make_response(data.to_csv())
resp.headers["Content-Disposition"] = "attachment; filename=export.csv"
resp.headers["Content-Type"] = "text/csv"
return resp
return jsonify({"msg":"Could not generate CSV File"})
I'd recommend using send_file(...) with a BytesIO (file stream) object:
from io import BytesIO
from flask import send_file
...
response_stream = BytesIO(data.to_csv().encode())
return send_file(
response_stream,
mimetype="text/csv",
attachment_filename="export.csv",
)
Keep in mind that you will not be able to open the download prompt when sending a POST request using AJAX. Instead, you will simply receive the file as an AJAX response. To solve this issue, you will have to take a look at this question:
download file using an ajax request
Maybe your code was already working and this was your problem – I can not tell from looking at it.
I finally figure it out. Basically I can store the user input using the session object available from the flask library. This allows different functions to access this rather then having to worry about creating global variables or passing them around via functions or objects.
Note 1- If the amount of user data that has to be saved is extensive then using Redis or some other type of in memory data storage would be a better choice in this case.
Save the csv file in static path and then use the that static path csv URL to get csv file in download form from browser.
I am trying to get data of "value" from a data file
{"success":"true","value":"500","items":"12","currency":"NOK"}
this is what i think should work.
<div class="value"></div>
<script>
$.get('URLTOFILE', function(data) {
var text = `Value: ${data.value|| "Not Found"}`
$(".value").html(text);
});
</script>
Is your json file hosted on a server somewhere? If so, are you getting any errors when you attempt to fetch it?
If the json file is simply a file on your computer, you won't be able to load it like that. If you are using webpack or another package manager to bundle your files, you can use import to import the file into your javascript file like so:
import json from "file.json";
console.log("My json: ", json);
// Rest of javascript file here
This assumes that you've set up your bundler to handle json files though. Webpack does this for you automatically. So if you're using it, then this should work. Not sure about other bundlers though.
But it's best to host the file on a server and fetch it, especially if the data changes constantly - such as from an API.
Lets say I have a yaml file which I want to validate in Angular6. If yaml file is parsed in json or other format successfully then say it's a valid yaml file otherwise it's not.
I found javascript and java has the solution for this question , but I wanted to do it using angular6.Is it possible to parse using angular and validate it?
I'm not sure WHY you'd want to parse a .yml file from Angular (vs., say, a standalone NodeJS app).
But sure.
The easiest way is probably to add a 3rd party library to your Angular build project (npm install --save), then invoke it from your Angular app.
js-yaml is a good choice: https://www.npmjs.com/package/js-yaml
EXAMPLE CODE (nodeJS):
yaml = require('js-yaml');
fs = require('fs');
// Get document, or throw exception on error
try {
var doc = yaml.safeLoad(fs.readFileSync('/home/ixti/example.yml', 'utf8'));
console.log(doc);
} catch (e) {
console.log(e);
}
I am trying to load some images from a file on a server to display on a list. I get 404 not found error
after asking in forums, I get that the request URL is wrong, it looks inside the localhost not inside the json file.
https://filehost.net/db54d37849f75ddd
in the code I have a service which returns a response. I use that response in a controller and to the view. I get other information but no images
if anybody has a solution that would be really great.
please attach also some code, in this way it is easier to help you. About the problem, do have correct form of $http GET request? I mean does your get request points to correct address on server? something like this
`
// Simple GET request example:
$http({
method: 'GET',
url: '/someUrl'
}).then(function successCallback(response) {
// this callback will be called asynchronously
// when the response is available
}, function errorCallback(response) {
// called asynchronously if an error occurs
// or server returns response with an error status.
});
`
you can check more here Angular $http
I've been trying to create a Web Service with play framework. I've searched some tutorial and resource about this and end up using the renderJSON() method to provide JSON RESTful web service.
But, there seems to be a problem with that when I try to consume the web service with JQuery. If I use JSON, it fails with this error Origin http://localhost is not allowed by Access-Control-Allow-Origin. Which seems to be a cross-domain problem. Then I try to use JSONP as the datatype when JQuery trying to consume the web service, again there's an parseError problem.
After some research, I found that to provide a web service to the JSONP request. We need to provide something like a callback function. So it's not enough to return only the JSON object to the client. If I'm not mistaken, The format should look something like {#callback-function}{#JSON-data}
How to make a Cross-Domain web service in Play Framework? Is there any workaround for this?
Is there anyway to keep the JSON format of a/a list of object to a string instead of render the object as JSON directly as done by calling renderJSON()?
Here is what I did. In my routes I set the format of the response to javascript with:
GET /api/projects.json Api.projects(format:'json')
Then for the controller in Api I used flexjson and did this:
public static void projects(String p) {
JSONSerializer json = new JSONSerializer();
List<Project> projects = Project.all().fetch(3);
renderJSON(p + '(' + json.serialize(projects) + ')');
}
So now jsonp calls can be made by hitting /api/projects.json?p=whatever and the return will be:
whatever([{"your":"json"}])
You can also use flexjson to only serialize the parts of the object that you want to expose.
Testing it with jquery:
$.ajax({
url: "http://api/projects.json",
dataType: "jsonp",
jsonp : 'p',
crossDomain : true,
success: function(data){
console.log(data);
}
});
This is working great but you can use Gson object directly instead of the flexjson object.