Parsing json using jquery undefined - javascript

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.

Related

html() function issue

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.

javascript/jquery indicate something is a variable

I have a function that injects user's data into html file
the json format is something like this:
{"Fname":"abc","LName":"cdf", "Phone":"123456";}
this is a function to inject data into html file:
function injectData(data){
$.each(data, function(key, value) {
//notice that in the "data.value", I want 'value' to be a variable
//so that when I loop over the array, data.value will become data.Fname,
//and then data.LName and then data.Phone
$("#"+key).html(' ' + data.value +'');
});
How can I force javascript to interpret 'value' as a variable first before calling data.value in order to get the real value from JSON object? This is a little bit confusing. Hope you understand .Thank you
Write something like:
for(key in data){ $("#"+key).html(' ' + data[key] +''); });

how to parse csv by csv-jQuery and generate report?

imagine that you have csv data like this that I can read them from a textarea on my web page:
A,10,USA
B,5,UK
A,2,USA
I am trying to use cs-jQuery to parse and process this data to get the following report:
A has ran 12 miles with average of 6.
B has ran 5 miles with average of 5.
The code that I have written looks like this:
<script>
$(document).ready(function() {
$('#calculate').click(function() {
$('#report').empty();
var data = $('#input').val();
var values = $.csv.toObjects(data);
$('#report').append(values);
alert(values);
});
});
</script>
but all I am getting is [object Object] [object Object]...
any suggestion on what I should do? any way to do this with jQuery functionality?
this function $.csv.toObjects() return array of objects
Useful for parsing multi-line CSV data into an array of objects
representing data in the form {header:value}. Unless overridden, the
first line of data is assumed to contain the headers.
You don't have header so you should use $.csv.toArrays() instead and iterate over that array:
$.each($.csv.toArrays(data), function(_, row) {
$('#report').append('<div>' + row[0] + ' has ran ' + row[1] + ' miles</div>');
});
if you want to use toObjects you need to put header
person,miles,country
A,10,USA
B,5,UK
A,2,USA
and access it using row.person row.miles and row.country

Parse JSON response from Servlet

Ok, Ive got a Java Servlet returning some JSON (In Application/JSON format). To do this, im using the GSON libary.
The Servlets GET method takes one paramater, ID. The servlet seems to be working, For example,chrome shows my AJAX GET request returning the following when the [Booking]ID paramater sent is 1.
0: {WidgetID:46, BookingID:1, X:393, Y:50, Content:Test1}
1: {WidgetID:47, BookingID:1, X:337, Y:251, Content:Test2}
2: {WidgetID:48, BookingID:1, X:97, Y:198, Content:Test3}
The problem I have is with parsing this response. Here is my JS code:
loadPositions() {
var BookingID =
if (BookingID != null && BookingID != "null")
{
var data = {"id" : BookingID};
$.getJSON("Widget", data, function(data) {
// Successfully got all this bookings widgets as JSON, TODO: Parse this!
});
}
}
What should I put in the "TODO: Parse this!" section?
I want to foreach over all the elements, and grab their data. I really suck at this JQuery stuff.
In the todo section, you should do the following to loop through all the arrays:
$.each(data, function(index,value){
// here index=0 & value.WidgetID=46, value.BookingId = 1, use it as you would like to.
})
Have a look at jQuery .each()
http://api.jquery.com/jQuery.each/
and for a good example of what you want to do...
http://api.jquery.com/jQuery.getJSON/
$.getJSON('ajax/test.json', function(data) {
var items = [];
$.each(data, function(key, val) {
items.push('<li id="' + key + '">' + val + '</li>');
});
$('<ul/>', {
'class': 'my-new-list',
html: items.join('')
}).appendTo('body');
});
Take a look at
https://github.com/acobley/jBoggyAppy/blob/HectorV2-Cassandra-0.7.0/WebContent/Scripts/index.js
the ShowScrollingTags function.

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