How do i retrieve data from json data - html

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.

Related

How to return csv file from json data using Flask?

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.

get json data from a public json file not REST api with React

I have a url similar to https://www.nonexistentsite.com/fubar.json where fubar.json is a public json file which will download to your file system if you navigate to the url with your browser. I have a React web app where I want to read that file directly so as to display some of its data. I don't want to bother with any kind of a backend that would download the file to the apps file system so that it can read it. I want the React front end to read it directly in it's client side code with a fetch or an axios call or something like that. I'm familiar with the typical situation where I have a REST url like https://www.nonexistentsite.com/fubar which I can call and get the data. I'm failing to find info on how to handle this situation.
You could use Axios to load the data from the json file.
Example usage;
axios.get('https://www.nonexistentsite.com/fubar.json')
.then(jsoncontent => {
console.log(jsoncontent);
//do stuff with jsoncontent here
});
Maybe I'm misunderstanding your question, but I believe if you are just needing to fetch the json from a hosted file, you should be able to do so with axios.get(url)

Import Json file from asset - Angular Production Build Issue

I am importing my json file from asset folder to read some configurations inside the app which works perfectly and I can change the json values based on my requirement
you can refer : https://www.techiediaries.com/import-local-json-files-in-typescript/
But in the production build version, When try to change the values from json file in the asset folder, it reads development data
after the investigation we found that json data are embedded in main-es5 file,
is there is any way to read json file using import method and we can change data dynamically (based on environment)
I would suggest the cleaner way to load it via HttpClient, and if it contains some configuration, I think this is the way you can change the data in assets and app will load again and again with HttpClient.
And if you want to read based on the environment, typescript import doesn't work.
Create a service, read the JSON via HttpClient based on pre-placed environment-specific JSON.
This is another alternative solution you can try.
Create one app.constant.ts file
//
// ===== File app.constants.ts
//
'use strict';
export const appConstants = {
'key':'value',
'key1':'value'
};
Import like this in component :
import {appConstants} from './../app.constants';
Use in component like this :
this.variable = appConstants.key;

How to validate a YAML file in angular6

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

How to upload json file through jmeter?

I have recorded my script to upload json file through Jmeter, but now I am facing the problem while uploading json file through jmeter which is on my local drive.
I am already done with following steps:
Either use full path to file, you're uploading, or copy it to JMeter's "bin" folder
Don't forget to tick Use multipart/form-data for HTTP POST box
Make sure you provide correct Parameter name and MIME Type
Getting exception in my response data:
{"Exception":"Object reference not set to an instance of an object."}
For me works like this. JSON example May be Your server prefer some specific headers? E.g. content type and so on
Why you're using json file?
If you facing problems with generating random JSON data, here is a JSR223 preprocessor:
import org.apache.commons.io.FileUtils;
def time = vars.get("stratup_time")
File myFile = File.createTempFile("upload-", "" );
// Generate Random length string and write to file
FileUtils.write(myFile, "{\"test\":\"$time\"", "UTF-8" )
// Store file name in variable.
vars.put( "filename", myFile.getCanonicalPath() )
And PostProcessor:
import org.apache.commons.io.FileUtils;
// Delete file and do not throw error
FileUtils.deleteQuietly(new File( vars.get("filename")));
In order to be able to record the file upload event you need to copy your .json file to JMeter's "bin" folder, this way HTTP(S) Test Script Recorder will be able to capture the request and generate necessary HTTP Request sampler. It will also populate the HTTP Header Manager
More information: Recording File Uploads with JMeter