Send JSON from Flask to JavaScript - javascript

I have a problem with send data from Flask to JavaScript. I have the informations whitch i get from the database and I add this data to the dictionary. Now I want to have JSON object in JavaScript for dispaly this information on a map. I use JSON.parse in JavaScript but it doesnt work.
Code in route.py
#app.route('/mapaa',methods=['GET','POST'])
def mapa():
slownik = {}
if 'event_form' in request.form:
name = request.form['name_event']
all_data = Event.query.filter_by(name=name).all()
for row in all_data:
slownik.update({'id':row.id})
slownik.update({'date_st':row.date_start})
slownik.update({'date_end':row.date_end})
slownik.update({'type':row.type})
slownik.update({'name':row.name})
slownik.update({'len_route':row.len_route})
slownik.update({'route':row.route})
return render_template('mapaa.html', title='Mapa',data=slownik)
In JavaScript mapa.js:
var parsed = JSON.parse('{{data | tojson}}');
console.log(data)
But it return:
VM475:1 Uncaught SyntaxError: Unexpected token { in JSON at position 1
at JSON.parse (<anonymous>)
What I am doing wrong ? I will add that date_end and date_start are datatime type. I tried to jsonify this dictionary too but it also doesnt work.

You can use this within your template mappa.html scripttag to parse thejson using [tojson`](https://jinja.palletsprojects.com/en/2.10.x/templates/#tojson) filter:
<script>
var parsed = {{ data | tojson | safe}};
console.log(parsed)
</script>

Related

Trying to parse JSON

I'm a complete beginner at node.js and trying to figure out how to send the contents of a JSON-object using REST. My code only results in an error saying "SyntaxError: Unexpected token  in JSON at position 0". I have used an online validator to see that the JSON is corrent. What is the issue?
// GET courses
const fs = require('fs');
app.get('/api/courses', function(req, res) {
var rawdata = fs.readFileSync('miun-db.json');
var data = JSON.parse(rawdata);
res.send(data.courses);
});
The data inside of your file is not formatted properly. Verify that miun-db.json is properly formatted before attempting to parse.
The issue is that your file is not properly formatted, check this out Working with JSON.
Also you can just import the JSON file and use it without fs.
import miunDb from './miun-db.json';
app.get('/api/courses', function(req, res) {
res.send(miunDb.courses);
});
According to the fs.readFileSync docs you can pass options to the function.
fs.readFileSync(path[, options])
If the encoding option is specified then this function returns a string. Otherwise it returns a buffer.
Since you don't pass any options you get a buffer and not the string content of the file.
Either you pass encoding to the function, e.g.
var rawdata = fs.readFileSync('miun-db.json', {encoding:'utf8'});
var data = JSON.parse(rawdata);
or you convert the buffer to string. E.g.
var rawdata = fs.readFileSync('miun-db.json');
var data = JSON.parse(rawdata.toString('utf8'));
Edit:
Your error message says you have an invalid character which is non printable. Seems like your file starts with a BOM (zero width no-break space (ZWNBSP)).
What happens if you try to remove it?
function stripBOM(content) {
content = content.toString()
// Remove byte order marker. This catches EF BB BF (the UTF-8 BOM)
// because the buffer-to-string conversion in `fs.readFileSync()`
// translates it to FEFF, the UTF-16 BOM.
if (content.charCodeAt(0) === 0xFEFF) {
content = content.slice(1)
}
return content
}
// [...]
var rawdata = fs.readFileSync('miun-db.json', {encoding:'utf8'});
var data = JSON.parse(stripBOM(rawdata));
// [...]
Credit goes to this gist.

Flask jinja2 renders new line from database field with errors in javascript

I am saving data in Flask application from a textarea.
After saving it I am trying to receive it back to html via javascript like this:
const item = "{{item}}";
It gives me the following error:
Uncaught SyntaxError: Invalid or unexpected token
On server side I am just retuning lik this:
item = Item.query.filter_by(id=id).first()
item=item.body
Error appears only when i save via textarea with a new line.
How can I fix this?
So far I tried: this works only if I change from '' and "" to template literals ``:
const item = `{{item}}`;
But I am not sure if this method is safe since it makes auto escaping. From jinja2 documentation: "String literals in templates with automatic escaping are considered unsafe because native Python strings are not safe."
Also const item = "{{item | safe}}"; seems not helping.

flask to javascript, sending json, running into invalid syntax error

I ran into this error while trying to send a pandas to_json object to front end using flask. the codes and errors look like this:
df_higg_msi_scored_manual = pd.read_csv(r'static/CSVFiles/higg_msi_scored_manual.csv')
materials = df_higg_msi_scored_manual.iloc[:33, 3]
material = materials.to_json(orient="values")
return render_template('/impacttool.html', material = material)
var user = JSON.parse('{{brand | tojson | safe}}');
and this is the error that pops up no matter how valid the resulting json file is:
depending on which json i send to the front end, i get either unexpected number or unexpected token, with unexpected token always matching the first alphabet of the first string in json. Could someone please help me figure this out? I've even tried print(material) on flask, then copied the exact json that was printed to the console, assigned that to a variable and sent it to the front end and it worked fine! but for some reason when i do to_json and assign it directly to a variable it throws this error. If someone knows how to fix it I would love to know. Thank you.
In your Javascript try to see what
console.log('{{brand | tojson | safe}}')
gets you because maybe you're trying to turn JSON data into JSON data so maybe also consider removing the | to json part of the variable call
Edit: calling variables doesn't work in files other than HTML files so try parsing the variable directly in the HTML file like so:
<script>
var user = JSON.parse('{{brand | tojson | safe}}')
</script>
or you could add it to a variable in the HTML file then parse it in the javascript file like so:
filename.html:
<script>
var jsondata = '{{brand | tojson | safe}}'
</script>
filename.js
var user = JSON.parse(jsondata)
I found a solution thanks to RaphSinai, it was because the {{ brands | tojson }} was formatted with extra double quotes as "[whatever...]" instead of just the [], so I changed the code from material = materials.to_json(orient="values") to json.loads(material = materials.to_json(orient="values")) and it worked fine.

Angular - parse json string created by json dumps

I couldn't find a helpful solution.
I work in python 3.6 (django rest-framwork) server side and angular 5 client side.
At the server:
class TypesView(APIView):
def get(self,request):
a = ['Cat','Dog']
j = json.dumps(a)
return Response(data=j, status=status.HTTP_200_OK)
I am trying to parse this at the client:
public getAnimalRaces(): Observable<string[]>{
const path = environment.apiEndpoint + "animals/races/"
return this._http_client.get<string[]>(path)
}
but I keep getting:
Error trying to diff '["Cat", "Dog"]'. Only arrays and iterables are allowed
This is what Being returned to the client:
"[\"Cat\", \"Dog\"]"
any ideas?
You are trying to iterate on a string.
You need to parse the response as JSON which will turn the response into an array which you can then use with *ngFor in the template for example.
this._http_client.get<string[]>(path)
.map((res) => JSON.parse(res));
Your response is stringified. In order to make it work, you have to send it as plain JSON on server side, or treat it as string and use JSON.parse() on client side.

Parse serialized Laravel cache data with Javascript

I'm using Laravel's cache feature to store keys in Redis. The key is stored as an array which Laravel's cache automatically serializes and unserializes into something like this:
"s:18:\"[\"bob\",\"dave\"]\";"
In PHP Laravel handles the parsing, but I need to access the data from Javascript. I am using the ioredis package in node. Everything works fine except for unserializing the data.
var Redis = require('ioredis');
var rediscache = new Redis();
rediscache.get("mykey", function (err, result) {
//Attempt to parse?
result = JSON.parse(result);
}
The key is fetched correctly, but is stuck as a string. I tried JSON.parse but this throws an error, I suppose because the format is wrong.
Unexpected token s at Object.parse (native)
How can it be correctly unserialised? I ideally want to get it as a Javascript array so a value can be altered, then re-serialised and saved back to Redis.
Many thanks.
What you have is a serialized string which contains a JSON string.
You can use a library if you don't want to write it yourself: https://github.com/naholyr/js-php-unserialize
After that, you'll have a JSON string, which you can then parse.

Categories

Resources