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;
}
Related
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.
I'm trying to parse JSON with jQuery, but I have some problem with it. I want to get JSON link.
const data = $.html(function(){
const entities = Entities.decode((this).toString());
const obj = JSON.parse(entities);
return {
url: obj.url
}
}).get();
console.log(data)
Result:
$.html(...).get is not a function
Code i'm trying to parse:
{"url": "http://download2018.com/ap/_com.GloftGGHM_2018-05-25.apk?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=IFVYHACUO60QSGWW9L9Z%2F20180622%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20180622T145015Z&X-Amz-Expires=2400&X-Amz-SignedHeaders=host&X-Amz-Signature=4bcec8896510ede49eb7150d684274fcefb47c036c82e852a316125b1fbdd742", "resp": "success"}
I'll appreciate your help !
The problem you have is caused by the fact that the JSON has been HTML encoded. To parse it back to an object you will need to first HTML decode it, which you can do using jQuery's html() and text() methods, like this:
var htmlEncodedJSON = "{"url": "http://download2018.com/ap/_com.GloftGGHM_2018-05-25.apk?X-Amz-Algorithm=AWS4-HMAC-SHA256&X-Amz-Credential=IFVYHACUO60QSGWW9L9Z%2F20180622%2Fus-east-1%2Fs3%2Faws4_request&X-Amz-Date=20180622T145015Z&X-Amz-Expires=2400&X-Amz-SignedHeaders=host&X-Amz-Signature=4bcec8896510ede49eb7150d684274fcefb47c036c82e852a316125b1fbdd742", "resp": "success"}";
var $el = $('<div />').html(htmlEncodedJSON);
var obj = JSON.parse($el.text())
console.log(obj.resp); // individual property
console.log(obj); // full object
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Note that this is not the ideal solution. The best solution would be to not HTML encode the JSON that's coming back from the server.
I am trying to load my data from my JSON file but apparently only the first attribute was loaded. I created an array by using jQuery push method to extract the data from my JSON file. When I see the array output from console.log, it looks fine.
I don't get what went wrong
my html
<h2>My message list </h2>
{{#msg}}
<img src= {{icon}} >
{{subject}}
{{detail}}
{{date}}
{{/msg}}
my Script
<script type="text/javascript">
function loadUser1(){
var template = $('#template').html();
Mustache.parse(template); // optional, speeds up future uses
$.getJSON( "messages.json", function( data ) {
console.log('loaded');
var messageslist = []; // create array here
$.each(data.messages, function (index, message) {
messageslist.push("{icon:'"+message.icon+"',subject:'"+message.subject+",detail:'"+message.detail+"',date:'"+message.date+"'}"); //push values here
});
console.log(messageslist);//see output
var rendered = Mustache.render(template,{"msg":messageslist});
$('#target').html(rendered);
});
}
</script>
The array shows in the console: (I have repetitive dummy data in json)
Array [ "{icon:'images/alert_bad.png',subject:'Supply Chain - Past Due,detail:'Gerry Harrison',date:'01/16/2015'}", "{icon:'images/alert_bad.png',subject:'Supply Chain - Past Due,detail:'Gerry Harrison',date:'01/16/2015'}", "{icon:'images/alert_bad.png',subject:'Supply Chain - Past Due,detail:'Gerry Harrison',date:'01/16/2015'}" ]
You're creating object as JSON string instead of javascript object, try this:
var rendered = Mustache.render(template,{"msg": data.messages});
the data.messages is already correct not need to push to another array.
I hope my question is not as stupid as I think it is...
I want to extract (the value of) a single variable from an JSONarray. I have this jquery code
$(document).ready(function(){
$("#gb_form").submit(function(e){
e.preventDefault();
$.post("guestbook1.php",$("#gb_form").serialize(),function(data){
if(data !== false) {
var entry = data;
$('.entries').prepend(entry);
}
});
});
});
the content of data looks like this ("MyMessage" and "MyName" are values written in a simple form from user):
[{"message":"MyMessage","name":"MyName"}]
the var "entry" should give (more or less) following output at the end:
"Send from -MyName- : -MyMessage-"
I'm not able to extract the single array values from data. I tried things like that:
var message = data['message'];
var name = data['name']
var entry = "Send from" + name + ":" +message;
but that gives "Send from undefined: undefined"
Hope you can help me with that.
you can do like this to get first item of array:
var msg = "Send from"+data[0].name + " "+data[0].message;
console.log(msg );
SAMPLE FIDDLE
UPDATE:
as you are using $.post you will need to explicitly parse response as json:
$.post("guestbook1.php",$("#gb_form").serialize(),function(data){
var response = jQuery.parseJSON(data);
var msg = "Send from"+response [0].name + " "+response [0].message;
console.log(msg );
});
To access an array you use the [] notation
To access an object you use the . notation
So in case of [{JSON_OBJECT}, {JSON_OBJECT}]
if we have the above array of JSON objects in a variable called data, you will first need to access a particular Json Object in the array:
data[0] // First JSON Object in array
data[1] // Second JSON Object in array.. and so on
Then to access the properties of the JSON Object we need to do it like so:
data[0].name // Will return the value of the `name` property from the first JSON Object inside the data array
data[1].name // Will return the value of the `name` property from the second JSON Object inside the data array
Hi I am new to json/jquery. Please help.
I have a database with list of cities/states. I get it and in the html document and use json_encode to get the json in a javascript object.
var json_obj = jQuery.parseJSON('<?php echo json_encode($query); ?>');
It looks like:
"[
{"city":"Aaronsburg","state_code":"PA"},
...
{"city":"Abbeville","state_code":"AL"}
]"
I am trying to use the following to access each city/state:
$.each(json_obj, function() {
$("<div>" + json_obj['state_code']+"/div>").appendTo('#test'); // I also tried json_obj.state_code
});
What I get in the output is:
undefined
...
undefined
What i need to do is actually print the city/state
Any help will be appreciated.
Thank you
The curreent value is passed by jQuery as:
$.each(json_obj, function(index, value) {
$("<div>" + value.state_code + "/div>").appendTo('#test');
});
Take a look at the specs.