print JSON string converted from python object using flask - javascript

I have this flask server running and i made this html file which has a script where when i clicked the button it will return a JSON string. However it kept giving me undefined instead.
I have this app.py code which gives me a python dict which i converted it to JSON
#app.route('/')
def helloworld():
#result = jsonify(student)
html_item = json.dumps(Marks, indent=2, separators=(', ', ': '))
return render_template('test1.html',data = html_item)
after this on the test1.html i have a script
<!DOCTYPE html>
<html>
<head>
<title>
JavaScript | Print content of object
</title>
</head>
<body style = "text-align:center;" id = "body">
<h1 style = "color:rgb(0, 2, 128);" >
{{data}}
</h1>
<p>
Print JavaScript Object.
</p>
<button onclick = "gfg_Run()">
print object
</button>
<p id = "GFG_DOWN" style
= "color:rgb(0, 2, 128); font-size: 20px; font-weight: bold;">
</p>
<script>
var el_down = document.getElementById("GFG_DOWN");
var GFG_object = {
prop_1: 'val_11',
prop_2: 'val_12',
prop_3: 'val_13'
};
function gfg_Run(data) {
el_down.innerHTML = data;
//el_down.innerHTML = JSON.stringify(GFG_object);
}
</script>
</body>
</html>
where I have tested that it can print out a js object by the line I commented out.
How should I print out a JSON string which in my case dataproperly?

You are not rendering your json string in your html template
Just having the word data is not going to take the data variable from your python script and replace it with your json. You need it surrounded in curly braces {{}}
//incorrect
myobject = data;
//correct
myobject = {{ data|safe }};
So to get your example working you could do
var GFG_object = {{data|safe}};
//took out the "data" from the parameter list
//since you aren't passing anything to gfg_Run()
function gfg_Run() {
//prints your object as a json string
el_down.innerHTML = JSON.stringify(GFG_object);
}
//if you are wanting print some property of your object
function gfg_Run() {
el_down.innerHTML = GFG_object["val"];
}

I am assuming you should know how to retrieve json data?!
If not, then visit: https://www.programiz.com/python-programming/json
Now that you know how to retrieve data stored in json format, and you should put the value straight into inner_html like:
el_down.innerhtml = data['val']
Or however, your json structure might be...
I think the way you are accessing json data is not correct. Please let me know after you try this solution.

Related

get variable from python into js

I'm creating an app that shows a webpage search according to a random word that is chosen by the program. I uploaded a dictionary into python to get a random word and now I want to put this word into the src= in my javascript code. What I need is some kind of placeholder that connects the 2 languages
Python
if request.method == 'GET':
#create an empty dictionary
d = {}
key = 0
#open dictionary file and store it in 'dic'
with open('dictionaries/nouns.rtf',encoding="utf8", errors='ignore') as dic:
#read every line and give it a number
for line in dic:
value = line.replace('\\', '')
key += 1
d[key] = value
#select a random number in the range of the dictionary (and store it in a variable)
rand = random.randrange(1, len(d) + 1)
#get the word with that number (and store it in a variable)
word = d[rand]
#print(word)
return render_template('/player.html', word = word)
Javascript
<script>
let is = document.getElementById('innerSpace');
query = encodeURI({{word}})
is.src = `https://www.bing.com/images/search?q=weirdest+${query}&form=QBLH&sp=-1&pq=cats&sc=8-4&qs=n&cvid=20659354CDFD49C6B03ED29A4F35EC64&first=1&tsc=ImageBasicHover`
</script>
To get the randomly generated word from Python to Javascript, you need to return a JSON response from your view.
from django.http import JsonResponse
if request.method == 'GET':
...
data = { 'word': word}
return JsonResponse(data)
You can then access the word within JavaScript using AJAX or Fetch. I will use Jquery as an example.
let is = document.getElementById('innerSpace');
$.ajax({
url: '/URL_for_your_view/',
action: 'GET',
// when the server returns data, the success method is run
success: function (data) {
query = encodeURI({{data.word}})
is.src = `https://www.bing.com/images/search?q=weirdest+${query}&form=QBLH&sp=-1&pq=cats&sc=8-4&qs=n&cvid=20659354CDFD49C6B03ED29A4F35EC64&first=1&tsc=ImageBasicHover`
}})
Now, the problem with this solution is that the view will no longer return the template player.html which seems essential in your code.
return render_template('/player.html', word = word)
To my knowledge, you cannot return a JSON response and a template in the same view. It's impossible.
So you need to use JavaScript to recreate the player.html code inside the success method and append it to the DOM.

How to pull JSON data on an HTML page

I would like to pull some information from an HTML page that has a script with JSON data in there. The script looks like this:
<script>
window.miPage = new pageInfo();
Details.initialize({
"firstName":"John",
"lastName":"Doe",
"timeFormat":["am","pm"],
"dateFormat":"M/d/yyyy",
"locale":"en"
});
</script>
I'm hoping to be able to pull the lastName value of "Doe" into a variable and use that as part of a jQuery or JS function.
Note, I can't modify the original script above.
Thanks!
Here's how you can do it with DOM.
for(let script of document.querySelectoAll("script")) {
if(script.ismyscript) { // a way to find out if it is the one, you can ignore it
let match = script.innerHTML.match(/^\s*Details\.initialize\((.*)\);$/m);
if(match) {
let json = match[1];
console.log(JSON.parse(json))
}
}
}

JavaScript, JSON, referencing by name

How do you reference a JSON object in JavaScript?
I have a JSON response from a Rest web service and trying to reference the contents of the response which I have parsed to JSON by way JSON.Parse(response)
Sample JSON:
{
"HotelListResponse":{
"customerSessionId":"",
"numberOfRoomsRequested":1,
"moreResultsAvailable":true,
"cacheKey":"",
"cacheLocation":"",
"cachedSupplierResponse":{
"#supplierCacheTolerance":"NOT_SUPPORTED",
"#cachedTime":"0",
"#supplierRequestNum":"101",
"#supplierResponseNum":"",
"#supplierResponseTime":"",
"#candidatePreptime":"14",
"#otherOverheadTime":"",
"#tpidUsed":"",
"#matchedCurrency":"true",
"#matchedLocale":"true"
},
"HotelList":{
"#size":"20",
"#activePropertyCount":"101",
"HotelSummary":[
{
"name":"name1"
},
{
"name":"name2"
}
]
}
}
}
How can I, for example reference the customerSessionId? And the second HotelSummary name?
For customerSessionId I have tried jsonObject.customerSessionId which returns undefined. For the second hotel summary name I have tried jsobObject.HotelList.HotelSummary[1].name which is undefined too.
Given the JSON string above parsed and assigned to a variable as such:
var response = JSON.Parse(jsonString);
you should be able to access it like this:
var customerSessionId = response.HotelListResponse.customerSessionId;
Here's the working solution fiddle
As you can see, you need to reference HotelListResponse,
so if your var result holds your json object, then you can fetch the values by using
var first = result.HotelListResponse.customerSessionId
var second = result.HotelListResponse.HotelList.HotelSummary[1].name

Parse json array using javascript

I have a json arry
var students = {"apResults":[{"offid":"267","item_name":"","offer_name":"fsdfsf","stlongitude":"77.5945627","stlatitude":"12.9715987"},
{"offid":"265","item_name":"","offer_name":"vess offer shops","stlongitude":"","stlatitude":""},
{"offid":"264","item_name":"","offer_name":"vess ofer shop","stlongitude":"","stlatitude":""},
{"offid":"263","item_name":"","offer_name":"ofer frm vess","stlongitude":"77.5943760","stlatitude":"12.9716060"},
{"offid":"262","item_name":"","offer_name":"offer hungamma","stlongitude":"77.5943760","stlatitude":"12.9716060"},
{"offid":"261","item_name":"","offer_name":"offer hungamma","stlongitude":"77.5943760","stlatitude":"12.9716060"},
{"offid":"260","item_name":"","offer_name":"offer1","stlongitude":"77.5943760","stlatitude":"12.9716060"},
{"offid":"259","item_name":"","offer_name":"offer","stlongitude":"77.5943760","stlatitude":"12.9716060"}]}
How i can parse this json arry using json.parse. I have tried this code
for(i=0;i<students.apResults.length;i++)
{
var contact = JSON.parse(students.apResults);
var offid = contact.offid;
alert(offid)
}
But its giving an error JSON.parse: unexpected character.Edited my question
That's not a json string, that's a regular javascript variable:
for(i=0;i<students.Maths.length;i++)
{
var contact = students.Maths[i];
var fullname = contact.Name;
alert(fullname)
}
for(i=0;i<students.apResults.length;i++)
{
var contact = JSON.parse(students.apResults[i].offid);
alert(contact)
}
JSON parses strings, not objects/arrays.
why need parsing when you can access it like students.Maths[i].Name
students is not a JSON array, it's an actual array. You don't have to parse because it's not a string. So you can access directly to the data you need:
for(i=0;i<students.Maths.length;i++) {
var contact = students.Maths[i];
var fullname = contact.Name;
alert(fullname)
}
You can't parse students because is not a JSON. It's simple object.
However this will work:
var students = JSON.stringify(students); // if you want to send data
students = JSON.parse(students); // after receiving make a object from it
//use like any object
for(i=0;i<students.Maths.length;i++)
{
var contact = students.Maths[i];
var fullname = contact.Name;
alert(fullname)
}
Of course it doesn't make sense to write it that way unless you send students data to other site or program.
Edit:
You don't need JSON in this code at all. But if you want to test JSON.parse() do it this way:
var students = { ... } // your data
var students = JSON.stringify(students); // students is `object`, make it `string`
students = JSON.parse(students); // now you can parse it, `students` is object again
for(i=0;i<students.apResults.length;i++) {
var contact = students.apResults; // no JSON
var offid = contact.offid;
alert(offid)
}
That should work.
What you have is a javascript object. So, you won't need the JSON.parse
for(i=0;i<students.Maths.length;i++)
{
var contact = students.Maths[i]);
var fullname = contact.Name;
alert(fullname)
}
this should be ok
The idea of JSON is for the exchange of objects represented as a structured string (in a nutshell). What you've got there is simply an object. It's unnecessary (and impossible) to parse and object that isn't JSON into a javascript object; what you have is the outcome of what you would expect from a parsed JSON string.

Processing javascript, objects and firebug

This is an edit of an earlier post. for a very novice question. I have a javascript function that is getting called with a data object. Data appears to be a json string. However the json string will not parse. How do I get parse this json string? Then how do I replace the contents of a div with value from the json string?
I get the following errors:
JSON.parse(data) dies with "unexpected character"
eval('(' + data + ')'); dies with error "missing ] after element list".
---- JSON string--------
http://jsonlint.com/ calls this a valid json string.
[{"cmd": "as", "id": "#calls", "val": "<h2> Missed Calls</h2><ul></ul>", "prop": "innerHTML"}]
---- html ----
<script type='text/javascript'>
function missed_calls_callback(data){
alert("Foo"); // (breakpoint) This alerts 'Foo'
alert(data.id); // This prints 'undefined'
var object1 = JSON.parse(data);
var object2 = eval('(' + data + ')'); // missing [
// How do I do the following?
// 1. divname = data.id
// 2. content = data.id.val
// 2. Replace contents of <div id="divname"> with content
}
</script>
<body>
And on my page I have div calls.
I want to fill div calls with
<div id="divname"> Put stuff here. </div>
</body>
What do you mean to "test" with firebug?
<body>
And on my page I have div calls.
I want to fill div calls with
<div id="divname"> Put stuff here. </div>
</body>
<script type="text/javascript">
data = {
cmd:"as",
id:"divname",
val:"<h2> My Content</h2>"
};
console.log(data);
document.getElementById(data.id).innerHTML=data.val;
</script>
jsFiddle
This was a tricky one. I will answer this for the group and the benefit of those who may have this same issue. The issue was invisible carriage returns inside a json string. data contained hidden characters that JSON.parse couldn't handle. I fixed the json string with a combination of methods to eliminate carriage returns that the javascript library couldn't handle.
------server side-------
render = render_to_string('templates/file.html', { 'tag': objects })
dajax = Dajax()
dajax.assign('tags','innerHTML', render)
jsonStr = dajax.json()
jsonStr = ''.join(unicode(jsonStr, 'utf-8').splitlines())
return jsonStr
-------client side-----
function my_callback(data){
var dString = JSON.stringify(data);
var myObject = JSON.parse(dString);
document.getElementById(myObject[0].id).innerHTML=myObject[0].val;
}

Categories

Resources