unable to read json file generated from gson library - javascript

This is part of javascript file I am using to read json file.
function initSearchInfo() {
var tagContent = "";
var tagsCount = 15;
var i = 0;
$.ajax({
type : "GET",
url : JSON_URL + SEARCH_HISTORY_JSON + EXT_JSON + versionParam,
dataType : "json",
contentType : "application/json",
async : false,
success : function(data) {
$.each(data.count, function(key, val) {
i++;
if (i > tagsCount) {
return false;
} else {
tagContent += "<li><a data-weight=" + val + " href='"
+ GLOBAL_SEARCH_URL + key + "'>" + key
+ "</a></li>";
}
});
$("#taglist").html(tagContent);
},
error : function(xhr, status, error) {
$("#tagCloud").html(getMessage(tagcloud.error));
$("#searchHistory").hide();
console.log(status);
}
});
}
I am able to read this json file(1) :
{
"count": {
"scm": {
"count": 22,
"date": "2013-05-08"
},
"java7": {
"count": 22,
"date": "2013-05-08"
},
"groovy": {
"count": 22,
"date": "2013-05-08"
},
"ldap": {
"count": 21,
"date": "2013-04-25"
}
},
"date": "10Oct2013"
}
But when I read this file (2):
{"count":"{\"ldap\":{\"count\":15,\"date\":\"2013-04-04\"},\"myplace\":{\"count\":12,\"date\":\"2013-05-08\"},\"ts-ws1\":{\"count\":11,\"date\":\"2013-05-08\"},\"hbase workshop\":{\"count\":11,\"date\":\"2013-05-08\"},"date":"11 Oct 2013"}
My code breaks when I try to read file (2).
File (2) is produced by gson library.But file (1) is written by me.

Seems like there is syntax error with the file giving error.
Value of "count" key is in double quotes and they don't end properly.

file(2) is not a valid json file. You can't have a double quote before the second { and also you can't have backslash before the double quotes. Please post your code that generates file(2).

Related

Unable to parse JSON filename object

I am unable to parse a JSON object (whatever.png) for some reason, I get [object%20Object] which is strange as I never have this issue, as its clearly simple to resolve or stringify and debug if in doubt.
My jQuery code:
$(function () {});
$.ajax({
url: '/shouts/get/ajax',
method: 'GET',
dataType: 'JSON',
success: function (res) {
res.forEach((element, i) => {
data = {
message: element['message'],
date: element['date'],
descr: element['descr'],
last_login: element['last_login'],
added: element['added'],
user: element['user'],
username: element['username'],
user_id: element['user_id'],
avatar: element['avatar'],
badges: element.badges
}
var result = XBBCODE.process({
text: data.message,
removeMisalignedTags: false,
addInLineBreaks: false
});
let allstring = '<div class="shoutbox-container"><span class="shoutDate" style="width:95px">' + jQuery.timeago(data.date) + ' <span style="color:#b3b3b3">ago</span><span id="user_badge_' + i + '"></span></span><span class="shoutUser"><a class="tooltip-shoutuser" title="' + data.username + '" href="/user/?id=' + data.user_id + '"><img src="' + data.avatar + '" class="shout-avatar" /></a></span><span class="shoutText">' + result.html + '</span></div><br>';
document.getElementById('shoutbox').innerHTML += allstring;
let badges = [];
data.badges.forEach(badge => {
badges.push('<img src="/images/avatars_gear/' + badge + '">').innerHTML += badges; // <--- Object bug
});
badges.forEach(badge => {
document.getElementById('user_badge_' + i).innerHTML += badge;
});
});
$('.shoutbox-container').filter(function () {
return $(this).children().length === 3;
}).filter(':odd').addClass('shoutbox_alt');
$('.shoutbox-container').each(function () {
$(this).parent().nextAll().slice(0, this.rowSpan - 1).addClass('shoutbox_alt');
});
$('.tooltip-shoutuser').tooltipster({
animation: 'grow',
delay: 200,
theme: 'tooltipster-punk'
});
}
});
JSON output from PHP:
[
{
"badges": [],
"username": "tula966",
"message": "perk added for [url=/user/?id=39691]tula966[/url]",
"avatar": "images/avatars/0f885488eb90548b5b93899615c5b838d2300bdb_thumb.jpg",
"date": "2022-02-04 01:00:01",
"last_login": "2022-02-03 12:36:06",
"user_id": "39691"
},
{
"badges": [
{
"image": "star.png",
"descr": " Star Power"
},
{
"image": "toolbox.png",
"descr": "Worker"
}
],
"username": "Tminus4",
"message": "testing testing",
"avatar": "images/avatars/8cc11eb4cb12c3d7e00abfba341c30b32ced49be_thumb.jpg",
"date": "2022-02-04 01:00:00",
"last_login": "2022-02-03 10:52:08",
"user_id": "1"
}
]
badge is not pushing the PNG file names from the JSON response to the DIV. I cant figure this out. This same code structure works perfectly on 3 other areas using the same JSON structure and logic, in fact more complex in our Site Polls area without any issues.
I also attempted to force the object with json_encode($array, JSON_FORCE_OBJECT) on the PHP side, which breaks the JS - and I have never needed to utilize that before in any case.
However this seems to differ greatly in this case. Any help is appreciated.

Unable to bind json data (api result) to dropdown using jquery/js in MVC

I want to bind json data returned by API to dropdownlist.
but unable to fetch value id and name.
Json Format :
{
"categories": [
{
"categories": {
"id": 1,
"name": "CatOne"
}
},
{
"categories": {
"id": 2,
"name": "CatTwo"
}
}
]
}
I am returning JsonResult, using
return Json(responseData, JsonRequestBehavior.AllowGet);
and in Jquery call ,I am using
$.ajax({
type: "POST",
url: "/Home/City",
contentType: "application/json; charset=utf-8",
global: false,
async: false,
dataType: "json",
success: function (jsonObj) {
var listItems = "";
//here I want to get id and name
});
}
});
You can populate dropdown from your json like following.
var json = {
"categories": [
{ "categories": { "id": 1, "name": "CatOne" } },
{ "categories": { "id": 2, "name": "CatTwo" } }
]
}
$.each(json.categories, function () {
$('select').append('<option value="' + this.categories.id + '">' + this.categories.name + '</option>')
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select></select>
You can just stick a break point (or debugger; statement) inside your success callback. Then you can inspect your jsonObj and it'll tell you exactly what you need to know.
In this case, you should be able to iterate on jsonObj.categories, and your id and name properties will be accessible via jsonObject.categories[i].categories.id and jsonObject.categories[i].categories.name
So your success method will look something like:
for(var i = 0; i < jsonObj.categories.length; i++) {
var category = jsonObj.categories[i].categories;
var id = category.id;
var name = category.name;
}
I would also suggest formatting your json differently, as other answers have suggested.

C# ListItemCollection to JSON, while keeping values and text items

I have created a web service (asmx file) that returns a serialized ListItemCollection with the following code.
public string getStates(string Country)
{
ListItemCollection lic = DBInterface.GetStates(Country);
var serialized = JsonConvert.SerializeObject(lic);
return serialized;
}
I call the web service via javascript when a user selects a country from a dropdown list using the following code.
//ajax function that uses web services to get states
function GetStates(val)
{
$.ajax({
type: "POST",
url: "/WebServices/getServerData.asmx/getStates",
data: JSON.stringify({Country: val}),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function (data) {
$("#ddlState").empty();
var parsed = JSON.parse(data.d);
for (var i = 0; i < parsed.length; i++) {
$("#ddlState").append("<option value='" + parsed[i] + "'>" + parsed[i] + "</option>");
}
},
error: function (data) {
alert(data.status + " " + data.statusText);
}
});
}
The issue is that I want to also keep not only the ListItemCollection text, but also it's value. However the "JsonConvert.SerializeObject only returns the text items. Can someone help to return the value and text so that I can populate the dropdown via javascript?
Thanks!
One thing you can use the JavaScriptSerializer() in System.Web.Script.Serialization:
ListItemCollection lic = new ListItemCollection() {
new ListItem("Display Text", "val1"),
new ListItem("Display Text 2", "val2"),
};
var ser = new JavaScriptSerializer();
var serialized = ser.Serialize(lic);
Results in (I took the liberty to format) :
[
{
"Attributes": {
"Keys": [],
"Count": 0,
"CssStyle": {
"Keys": [],
"Count": 0,
"Value": null
}
},
"Enabled": true,
"Selected": false,
"Text": "Display Text",
"Value": "val1"
},
{
"Attributes": {
"Keys": [],
"Count": 0,
"CssStyle": {
"Keys": [],
"Count": 0,
"Value": null
}
},
"Enabled": true,
"Selected": false,
"Text": "Display Text 2",
"Value": "val2"
}
]

How to read array inside JSON Object this is inside another array

I am newbie to JSON, I am parsing a JSON Object and i was struck at a point where i have to read the array Elements inside a Object, that is again in another array..
Here is MY JSON
{
"DefinitionSource": "test",
"RelatedTopics": [
{
"Result": "",
"Icon": {
"URL": "https://duckduckgo.com/i/a5e4a93a.jpg"
},
"FirstURL": "xyz",
"Text": "sample."
},
{
"Result": "",
"Icon": {
"URL": "xyz"
},
"FirstURL": "xyz",
"Text": "sample."
},
{
"Topics": [
{
"Result": "",
"Icon": {
"URL": "https://duckduckgo.com/i/10d02dbf.jpg"
},
"FirstURL": "https://duckduckgo.com/Snake_Indians",
"Text": "sample"
},
{
"Result": "sample",
"Icon": {
"URL": "https://duckduckgo.com/i/1b0e4eb5.jpg"
},
"FirstURL": "www.google.com",
"Text": "xyz."
}
]
}
]
}
Here I need to read URL ,FIRSTURL and Text from RelatedTopics array and Topics array..
Can anyone help me. Thanks in advance.
Something like this
function (json) {
json.RelatedTopics.forEach(function (element) {
var url = element.Icon ? element.Icon.URL : 'no defined';
var firstURL = element.FirstURL ? element.FirstURL : 'no defined';
var text = element.Text ? element.Text : 'no defined';
alert("URL: " + url + "\nFirstURL: " + firstURL + "\nText: " + text);
if (element.Topics)
{
element.Topics.forEach(function (topicElement) {
alert("Topics - \n" + "URL: " + topicElement.Icon.URL + "\nFirstURL: " + topicElement.FirstURL + "\nText: " + topicElement.Text);
});
}
});
};
Look fiddle example
Loop through json Array like,
for(var i=0; i< RelatedTopics.length;i++){
if($.isArray(RelatedTopics[i])){
for(var j=0; j< RelatedTopics[i].Topics.length;j++){
var topics=RelatedTopics[i].Topics[j];
var text = topics.Text;
var firsturl = topics.Firsturl;
var url = topics.Icon.url;
}
}
}
if you want push it an array variable

Unable to populate Table with Ajax Json response

I am sending this valid JSON as a response from my webservice call
[
[
{
"id": 123,
"vendorName": "PoppyCounter",
"item": "Chocltae"
},
{
"id": 1234,
"vendorName": "PoppyCounter",
"item": "Chocltae"
},
{
"id": 12345,
"vendorName": "PoppyCounter",
"item": "Chocltae"
},
{
"id": 123456,
"vendorName": "MahalakshmiCounter",
"item": "Chocltae"
}
]
]
This is my Jquery
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'http://192.168.2.46:8086/Poller/poll/initial',
jsonpCallback: 'jsonCallback',
dataType: 'jsonp',
success: function (response) {
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.id + '</td><td>' + item.vendorName + '</td><td>' + item.item + '</td></tr>';
});
$('#records_table').append(trHTML);
},
error: function (e) {
$("#divResult").html("WebSerivce unreachable");
}
});
});
<table id="records_table" border='1'>
<tr>
<th>Rank</th>
<th>Content</th>
<th>UID</th>
</tr>
With this the result is looking like this in browser
I am editing my question
Edited Part
Due to the cross domain restrictions , i am forming my JSON into jsonp as shown below
This is my ajax jquery request
$(document).ready(function() {
$.ajax({
type: 'GET',
url: 'http://192.168.2.46:8086/Poller/poll/initial',
jsonpCallback: 'jsonCallback',
dataType: 'jsonp',
jsonp: false,
success: function (response) {
var trHTML = '';
$.each(response, function (i, item) {
trHTML += '<tr><td>' + item.id + '</td><td>' + item.vendorName + '</td><td>' + item.item + '</td></tr>';
});
$('#records_table').append(trHTML);
doPoll();
},
error: function (e) {
$("#divResult").html("WebSerivce unreachable");
}
});
});
Due to the jsonCallback , its not forming a valid JSON response and i am getting undefined when forming the table
IS there anyway i can from the valid JSON response ??
jsonCallback([
[
{
"id": 123,
"vendorName": "PoppyCounter",
"item": "Chocltae"
},
{
"id": 1234,
"vendorName": "PoppyCounter",
"item": "Chocltae"
},
{
"id": 12345,
"vendorName": "PoppyCounter",
"item": "Chocltae"
},
{
"id": 123456,
"vendorName": "MahalakshmiCounter",
"item": "Chocltae"
}
]
])
You have to have one more $.each() loop:
$.each(response, function (i, item) {
$.each(item, function(_, o){
trHTML += '<tr><td>' + o.id + '</td><td>' + o.vendorName + '</td><td>' + o.item + '</td></tr>';
});
});
You appear to be having another array in that result. Try to loop one more time, like this for instance: http://jsfiddle.net/yH942/1/
$.each(jsonResponse, function(key, array) {
$.each(array, function(k, object) {
// your code goes here
});
});
Parse your object after receiving or use $.getJSON instead of $.ajax. You are trying to use a string as an object.
success: function (response) {
response = JSON.parse(response);
}
your data is an array in an array, and you consider it only as an array
try to do the same each loop on response[0] for example
EDIT
I'm not sure you can use jquery each on a JSON object, instead you should use :
for(var i in response) {
response[i]; // do something with it
}

Categories

Resources