Unable to parse JSON filename object - javascript

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.

Related

Formatting JSON for email body

I've JSON in the following format that I'm trying to insert into outlook/email client's body using
location.href = "mailto:" + "email#domain.com" + "?subject=" + "Notes" + "&body=" + JSON.stringify(data, null, 4);
Giving 4 spaces JSON.stringify(data, null, 4)
[
{
"page": "article_0_page_0",
"note": "Note 1"
},
{
"page": "article_0_page_1",
"note": "Note 2"
}
]
I want to output as
<b>article_0_page_0</b>\n\r
Note 1
<b>article_0_page_1</b>\n\r
Note 2
Any regular expression solution please.
Edit: My attempt
var str = "";
for(var i=0; i<data.length; i++) {
str += "<strong>" + data[i].page + "</strong><br>" + data[i].note + "<br><br>";
}
I think the above answer is ok if you have a flat structure.
If you want a more holistic approach for email specifically, I have found this to work really well.
const data = {...}
JSON.stringify( data, null, ' ' ).split( '\n' ).join( '<br>' );
This will convert something like this
const json = {
"status": "ok",
"config": {
"gotIt": "yes",
"transform": [
null
]
}
}
Into something like this
{<br>&nbsp"status": "ok",<br>&nbsp"config": {<br>&nbsp&nbsp"gotIt": "yes",<br>&nbsp&nbsp"transform": [<br>&nbsp&nbsp&nbspnull<br>&nbsp&nbsp]<br>&nbsp}<br>}
Email clients will render this as the following
{
"status": "ok",
"config": {
"gotIt": "yes",
"transform": [
null
]
}
}
This is done by using the additional parameters in JSON.stringify which I don't see used very often if you want to read more about these parameters here is the link for them.
Here ya go
var json = [
{
"page": "article_0_page_0",
"note": "Note 1"
},
{
"page": "article_0_page_1",
"note": "Note 2"
}
];
var out = "";
for (var key in json) {
if (json.hasOwnProperty(key)) {
out += "<b>"+json[key].page+"</b>\r\n"+json[key].note+"\r\n\r\n";
}
}
console.log(out);
Example Here: https://jsfiddle.net/q5r4gdcn/1/
This is what I used to convert basic JSON to "readable" for email:
let json = {
"key": "asdas",
"query": "",
"hints": {
"nested1": "blahblah"
}
}
let prettyJSON = JSON.stringify(json, null, ' ')
.split('\n')
.join('<br> ')
.split('<br> }').join('<br>}')
document.body.innerHTML += `<div>${prettyJSON}</div>`

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

json obj with array

How can i loop the contacts inside my json object using javascript?
{
"success": 1,
"contacts": [
{
"cName": "testing",
"cmail": "testMail",
"ctlf": "testPhone"
},
{
"cName": "testing",
"cmail": "testMail",
"ctlf": "testPhone"
}
],
"fName": "Actura",
"fAdr": "langdyssen 5, 8200 Aarhus N",
"date": "14-9-2019"
}
I've tried using the code below, but it only displayed 0 and 1 at the console
$.getJSON("./ajax/get.php", {
type: "printer",
placement: "firm",
id: id
}).done(function (data) {
if (data.success == 1) {
//$('table#printerInfo').append("<tr><td>Printer ID</td><td>" + data.id + "</td></tr>").append("<tr><td>M&aeligrke</td><td>" + data.brand + "</td></tr>").append("<tr><td>Model</td><td>" + data.model + "</td></tr>").append("<tr><td>Farve</td><td>" + data.color + "</td></tr>");
$('table td#firmName').append('<span class="glyphicon glyphicon-home"></span> ' + data.fName);
$('table td#firmAdr').append('<span class="glyphicon glyphicon-globe"></span> ' + data.fAdr);
$('table td#firmDate').append('<span class="glyphicon glyphicon-calendar"></span> ' + data.date);
for (var contact in data.contacts) {
console.log(contact);
}
console.log(data);
toolTip();
}
else {
alert("Der er sket en fejl: " + data.error);
}
});
Replaced data with test data, and due to 'too much code' ill be adding some ekstra text since i cant delete the question due to answers
Use code below instead:
for (var i in data.contacts) {
console.log(data.contacts[i]);
}

unable to read json file generated from gson library

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).

Custom Javascript Won't Run in Joomla

I am using Joomla-3 for my websites and I have created a simple small JavaScript(ajax) file which I attached through the template config file(as seen on the template's documentation).
I also added my html in an article(without TinyMCE etc so I know it accepts my code). The script works fine in a simple .html or .php file but it doesn't work along with Joomla.
My script has 2 dependent ajax dropdown menus(static content). Do you have any ideas on what could go wrong?
Thank you in advance!
PS. You can find the code of my JavaScript here.
Here's the code:
$(window).load(function () {
var services = [];
services['service1'] = [{
"name": "Giannis",
"url": "giannis"
}, {
"name": "Kostas",
"url": "kostas"
}, {
"name": "Fillipos",
"url": "fillipos"
}
];
services['service2'] = [{
"name": "Maria",
"url": "maria"
}, {
"name": "Peter",
"url": "peter"
}, {
"name": "Jack",
"url": "jack"
}
];
services['service3'] = [{
"name": "Dimitris",
"url": "dimitris"
}, {
"name": "Takis",
"url": "takis"
}, {
"name": "Gianna",
"url": "gianna"
}
];
jQuery(document).ready(function () {
jQuery("#services").change(function () {
var selectedService = $(this).val();
$('#doctors').children().remove();
$('#doctors').append('<option value="Null">Click to select a Doctor</option>');
jQuery.each(services[selectedService], function (ind, val) {
$('#doctors').append('<option value="' + this.url + '">' + this.name + '</option>');
})
});
jQuery("#doctors").change(function () {
var redirServ = $('#services option:selected').val();
var thePersonObject = services[redirServ];
var goThere = $(this).val();
var fullurl = 'http://www.website.com/our-services/' + redirServ + '/item/' + goThere;
alert(fullurl);
//location.href = 'http://www.website.com/our-services/' + redirServ + '/item/' + goThere;
});
});
});
Tried this?
$(window).on(‘load’, function(){
// AWESOMENESS
})

Categories

Resources