I'm trying to use this code to prettify a JSON object retrieved from another service and return it in a static page (has to be).
The javascript functions work but I'm having issues dealing with the stringified object.
It works fine encoding for example before the return statement for the html
json = "{\"a\":\"b\",\"c\":\"d\"}"
and not using stringify but it does not using JSON.stringify with a real JSON object instead.
function getStaticResponse(jsonObjectRetrieved){
return '<html>'
+ '<head>'
+ '<title>' + 'title' + '</title>'
+ '<link rel="stylesheet" type="text/css" href="'
+ '/something' + '">'
+ '</head>'
+ '<body>'
+ '<pre class="json-output box bg-color-weight-6 font-calibri">'
+ jsonFormat(JSON.stringify(jsonObjectRetrieved))
+ '</pre>'
+ '</body>'
+ '</html>';
}
function transformJson(k, v) {
if (k === 'href' && typeof v === 'string') {
var label = v.replace(/&/gi, '&');
return '<a href=' + v + '>' + label + '</a>';
}
return v;
}
function jsonFormat(jsonString) {
var jsonObj = JSON.parse(jsonString, transformJson);
return JSON.stringify(jsonObj, undefined, 2)
.replace(/\s"(\w*)":/g, ' "<span class="key">$1</span>":')
.replace(/:\s"(.*)"/g, ': "<span class="string">$1</span>"');
};
Many thanks
Try removing call to JSON.stringify at jsonFormat(JSON.stringify(jsonObjectRetrieved))
var json = "{\"a\":\"b\",\"c\":\"d\"}";
function getStaticResponse(title, jsonObjectRetrieved) {
return '<html>'
+ '<head>'
+ '<title>' + title + '</title>'
+ '<link rel="stylesheet" type="text/css" href="'
+ 123 + '">'
+ '</head>'
+ '<body>'
+ '<pre class="json-output box bg-color-weight-6 font-calibri">'
+ jsonFormat(jsonObjectRetrieved)
+ '</pre>'
+ '</body>'
+ '</html>';
}
function transformJson(k, v) {
if (k === 'href' && typeof v === 'string') {
var label = v.replace(/&/gi, '&');
return '<a href=' + v + '>' + label + '</a>';
}
return v;
}
function jsonFormat(jsonString) {
var jsonObj = JSON.parse(jsonString, transformJson);
return JSON.stringify(jsonObj, null, 2)
.replace(/\s"(\w*)":/g, ' "<span class="key">$1</span>":')
.replace(/:\s"(.*)"/g, ': "<span class="string">$1</span>"');
};
document.write(getStaticResponse("abc", json));
Related
I use a tag onclick function to delete specific documents.
I call the function with three arguments.
but my regex does not include a specific case.
Generally, it works, like "test".
but some case doen't work.
Like this case => "St. John's"
//return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + value + '\'' + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
//return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + '/\"'+ value + '\'' + '\"/ ' + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
const itemsArray = tableData.map(function(item) {
var key = Object.keys(item)[0];
var value = Object.values(item);
//return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + value + '\'' + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
//return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + '/\"'+ value + '\'' + '\"/ ' + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '<a href="javascript:void(0);" onclick="deleteName(\'' + key + '\'' + ',\'' + "\"" + value + "\"" + ',\'' + regionCode + '\');" >[ 삭제 ]</a>' + '</td></tr>';
});
this is expected key value example
const key = "en";
const value = "test"; // it works
const value = "St. John's"; // it doesn't work.
const regionCode = "AG-ANU";
if onclick function call success,
it calls this function
function deleteName(key, value, regionCode) {
$.ajax({
url: "http://localhost:8080/api/v1/regions/" + regionCode + "/names?lang=" + key + "&name=" + value,
method: "DELETE",
success: function() {
alert("삭제되었습니다.");
location.reload();
},
error: function(err) {
console.log(err);
}
});
}
I need help for value part regex expression.
It is not good way, but I solved like this.
const itemsArray = tableData.map(function(item) {
var key = Object.keys(item)[0];
var value = Object.values(item)[0];
var valueStr = JSON.stringify(value);
var valueString = value.replace(/'/gi, "\\\'");
var keyValueRegionCode = key + "|" + valueString + "|" + regionCode;
return '<tr><td>' + key + '</td><td>' + value + '</td><td>' + '[ 삭제 ]' + '</td></tr>';
});
then calls keyValueRegionCode
function deleteName(keyValueRegionCode) {
var keyValue = keyValueRegionCode.split("|")[0];
var nameValue = keyValueRegionCode.split("|")[1];
var regionCode = keyValueRegionCode.split("|")[2];
$.ajax({
url: "http://localhost:8080/api/v1/regions/" + regionCode + "/names?lang=" + keyValue + "&name=" + encodeURIComponent(nameValue),
method: "DELETE",
success: function() {
alert("삭제되었습니다.");
location.reload();
},
error: function(err) {
console.log(err);
}
});
}
1) value.replace(/'/gi, "\\'"); -> this regex makes single apostrophe like this. (\')
2) make parameters one for calling function easily .
I want to make a switch for declaring variables inside each loop, like this
switch (label) {
case "Users":
content = item.username+ ' ' + item.firstname + ' '
+ item.lastname + '('+ item.organization + ')';
break;
default:
}
$.each(result, function (i, item) {
html += "<option value ='" + item.id + "'>" + content + "</option>";
});
But since item variable hasn't defined yet I will get an ReferenceError.
Moving switch inside loop will make It really slow.
Is this even possible to declare loop variables outside of scope?
function selectorAddEdit(label, tag, result, labelconf) {
var idtag = tag+"s";
var none = "<option value='None'>None</option>";
var labelHead = (labelconf=="head") ? "<div class='selectTitles'><label>"+label+"</label></div>" : "";
switch (label) {
case "Users":
var content = item.username + ' ' + item.firstname + ' ' + item.lastname + '('+ item.organization + ')';
break;
default:
}
var html = labelHead + "<select name='" + tag + "' class='" + tag + "'>";
$.each(result, function (i, item) {
html += "<option value ='" + item.id + "'>" + content + "</option>";
});
html += "</select></div>";
$("." + idtag).html(html);
}
Declare the content as a global variable
var content="";
switch (label) {
case "Users":
content = item.username+ ' ' + item.firstname + ' ' + item.lastname + '('+ item.organization + ')';
break;
default:
}
$.each(result, function (i, item) {
html += "<option value ='"+item.id+"'>"+content+"</option>";
});
This is assuming that item is distinct/unique and therefore you want the switch statement to be re-evaluated at each iteration of loop. What you can do is to use a method/function that returns the value, after evaluating a given condition:
var getOptionContent = function(item) {
switch (label) {
case "Users":
return item.username + ' ' + item.firstname + ' ' + item.lastname + '(' + item.organization + ')';
default:
return '';
}
}
var html = labelHead + "<select name='" + tag + "' class='" + tag + "'>";
$.each(result, function(i, item) {
html += "<option value ='" + item.id + "'>" + getOptionContent(item) + "</option>";
});
I am pulling address location information from a google spreadsheet and using it to create buttons. When you click on a button it then should open and populate the data for that location in a new page or if need into a dialog box.
How do you pass the information to a new page and complete the if statement? Everything works great if I manually add the entry.id.$t string in the last if statement.
$(document).ready(function () {
$(function FISLocations() {
$.getJSON("https://spreadsheets.google.com/feeds/list/GoogleSpreadsheetKey/od6/public/values? alt=json-in-script&callback=?",
function (data) {
$('.loc').append('<ul class="collapsibleList" id="list"><li><label for="mylist-node1" class="css_btn_classlist">Alabama</label><input type="checkbox" id="mylist-node1" /><ul class="loclist"></ul></li></ul>');
$.each(data.feed.entry, function (i, entry) {
var item = '<span style="display:none ">' + entry.id.$t + '</span>';
item += ' ' + entry.gsx$cityst.$t;
if (entry.gsx$state.$t == "AL") {
$('.loclist').append('<li>' + item + '</li>');
};
});
$('.poploc').append('<div class="items"></div>');
$.each(data.feed.entry, function (i, entry) {
var itemp = '<span style="display:none ">' + entry.id.$t + '</span>';
itemp += '' + entry.gsx$address1.$t + '<br/>';
itemp += ' ' + entry.gsx$city.$t + ', ';
itemp += ' ' + entry.gsx$state.$t;
itemp += ' ' + entry.gsx$postal.$t + '<br/>';
itemp += ' ' + entry.gsx$phone.$t + '<br/>';
itemp += ' ' + entry.gsx$fax.$t + '<br/>';
itemp += '<div class="px12bold"> ' + entry.gsx$email.$t + '<br/ ></div>';
itemp += '<div class="locmid"><br/><a ' + entry.gsx$androidloc.$t + 'class="css_btn_classsmall noselect">Map Us</a>';
itemp += ' Email Us ';
itemp += ' Call us </div>';
if (entry.id.$t == ? ? ? ? ? ? ) {
$('.items').append('<br>' + itemp + '</span><br/>');
};
});
});
});
});
I have a shout box on my Joomla site that is producing this error.
This is the Error:
[Error] TypeError: 'undefined' is not an object (evaluating 'config['show_photos']')
And javascript code is:
function prepareShout(json, config, permissions, data)
{
html = '<div class="shoutbox-row" id="shout-' + json['s_id'] + '">';
html += '<div class="shoutbox-member">';
if (config['show_photos'])
{
if (json['s_mid'] != 0)
{
if (config['profiles'])
{
html += '<a class="shoutbox-avatar" href="' + json['s_avatar']['link'] + '" title="' + data['ptitle'] + '"><img src="' + json['s_avatar']['image'] + '"></a>';
}
else
{
html += '<span class="shoutbox-avatar"><img src="' + json['s_avatar']['image'] + '"></span>';
}
}
else
{
html += '<span class="shoutbox-avatar"><img src="' + json['s_avatar']['image'] + '"></span>';
}
}
Is it possible to fix this issue?
just confirm your config object has a value as well like this
if (config && config['show_photos'])
...
if (config && config['profiles']){
...
I've been learning via jQuery how to shorten things up. I was wondering if this script can be expressed in a less verbose way? I don't like how everything sits on one huge line.
items.push('<li id="' + key + '">' + ' (key: ' + key + ')(value: ' + val.value + ')(type: ' + val.type + ') (range: ' + val.range + ') (clone: ' + val.clone + ') (archive: ' + val.archive + ') (access: ' + val.access + ')</li>')
Assuming that the object will always have the correct key/values:
str = '';
for (var item in val) {
str += '(' + item + ': ' + val[item] + ')';
}
$("<li>").attr('id', key).text(' (key: ' + key + ')' + str);
http://jsfiddle.net/36Nyu/
If items is another element, you can do something like this.
var str;
for(var i in val)
str += '('+ i +': '+ val[i] +')';
$('<li>', {
id: key,
text: str
}).appendTo(items);
You could use jquery tmpl, or similar:
var template = '(key: ' + key + ')(value: {{value}})(type: {{type}}) (range: {{range}}) (clone: {{clone}}) (archive: {{archive}}) (access: {{access}})';
$('<li />').attr('id', key).html($.tmpl(template, val));
Or, use a string.Format equivalent:
String.prototype.format = function () {
var args = arguments;
return this.replace(/\{\{|\}\}|\{(\d+)\}/g, function (m, n) {
/* Allow escaping of curly brackets with {{ or }} */
if (m === '{{') { return '{'; } else if (m === '}}') { return '}'; }
return typeof args[n] != 'undefined' ? args[n] : '{' + n + '}';
});
};
var text = '(key: {0})(value: {1})(type: {2}) (range: {3}) (clone: {4}) (archive: {5}) (access: {6})'.format(key, val.type, val.range, val.clone, val.archive, val.access);
Assuming you're appending all of the key/value pairs in the val object, doing something like this would be pretty maintainable:
var liPrefix = '<li id="' + key + '">(key: ' + key + ')',
liSuffix = '</li>',
liData = '';
$.each(val, function(k, v) {
liData += ' (' + k + ': ' + v + ')';
});
items.push(liPrefix + liData + liSuffix);
See demo