I have a code, where it generates a json viewer from the input json
When the dropdown is clicked it should download the current clicked json
My code downloads something else, not sure from where thats coming from
I have tried with
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/[email protected]/dist/css/bootstrap.min.css" rel="stylesheet">
<script src=" https://cdn.jsdelivr.net/npm/[email protected]/dist/js/bootstrap.bundle.min.js"></script>
</head>
<body>
<script>
! function() {
var e = `/* Syntax highlighting for JSON objects */
.json-editor-blackbord {
background: #fff;
color: #000;
font-size: 13px;
font-family: Menlo, Monaco, Consolas, "Courier New", monospace;
}
@media screen and (min-width: 1600px) {
.json-editor-blackbord {
font-size: 14px;
}
}
ul.json-dict,
ol.json-array {
list-style-type: none;
margin: 0 0 0 1px;
border-left: 1px dotted #525252;
padding-left: 2em;
}
.json-string {
/*color: #0B7500;*/
/*color: #BCCB86;*/
color: #0b7500;
}
.json-literal {
/*color: #1A01CC;*/
font-weight: bold;
color: #1a01cc;
}
.json-url {
color: #0969da;
}
.json-property {
color: #222;
line-height: 160%;
font-weight: 500;
}
/* Toggle button */
a.json-toggle {
position: relative;
color: inherit;
text-decoration: none;
cursor: pointer;
}
a.json-toggle:focus {
outline: none;
}
a.json-toggle:before {
color: #aaa;
content: "\25BC";
/* down arrow */
position: absolute;
display: inline-block;
width: 1em;
left: -1em;
}
a.json-toggle.collapsed:before {
transform: rotate(-90deg);
/* Use rotated down arrow, prevents right arrow appearing smaller than down arrow in some browsers */
-ms-transform: rotate(-90deg);
-webkit-transform: rotate(-90deg);
}
/* Collapsable placeholder links */
a.json-placeholder {
color: #aaa;
padding: 0 1em;
text-decoration: none;
}
a.json-placeholder:hover {
text-decoration: underline;
}`,
o = function(e) {
var o = document.getElementsByTagName("head")[0],
t = document.createElement("style");
if (o.appendChild(t), t.styleSheet) t.styleSheet.disabled || (t.styleSheet.cssText = e);
else try {
t.innerHTML = e
} catch (n) {
t.innerText = e
}
};
o(e)
}(),
function(e) {
function o(e) {
return e instanceof Object && Object.keys(e)
.length > 0
}
function t(e) {
var o = /^(ftp|http|https)://(w+:{0,1}w*@)?(S+)(:[0-9]+)?(/|/([w#!:.?+=&%@!-/]))?/;
return o.test(e)
}
function n(e, s) {
var l = "";
if ("string" == typeof e) e = e.replace(/&/g, "&")
.replace(/</g, "<")
.replace(/>/g, ">"), l += t(e) ? '"<a href="' + e + '" class="json-string json-url">' + e + '</a>"' : '<span class="json-string">"' + e + '"</span>';
else if ("number" == typeof e) l += '<span class="json-literal json-literal-number">' + e + "</span>";
else if ("boolean" == typeof e) l += '<span class="json-literal json-literal-boolean">' + e + "</span>";
else if (null === e) l += '<span class="json-literal json-literal-null">null</span>';
else if (e instanceof Array)
if (e.length > 0) {
l += '[<ol class="json-array">';
for (var r = 0; r < e.length; ++r) l += "<li>", o(e[r]) && (l += '<a href class="json-toggle"></a>'), l += n(e[r], s), r < e.length - 1 && (l += ","), l += "</li>";
l += "</ol>]"
} else l += "[]";
else if ("object" == typeof e) {
var a = Object.keys(e)
.length;
if (a > 0) {
l += '{<ul class="json-dict">';
for (var i in e)
if (e.hasOwnProperty(i)) {
l += "<li>";
var c = s.withQuotes ? '<span class="json-string json-property">"' + i + '"</span>' : '<span class="json-property">' + i + "</span>";
l += o(e[i]) ? '<a href class="json-toggle">' + c + "</a>" : c, l += ": " + n(e[i], s), --a > 0 && (l += ","), l += "</li>"
} l += "</ul>}"
} else l += "{}"
}
return l
}
e.fn.jsonViewer = function(t, s) {
return s = s || {}, this.each(function() {
var l = n(t, s);
o(t) && (l = '<a href class="json-toggle"></a>' + l), e(this)
.html(l), e(this)
.off("click"), e(this)
.on("click", "a.json-toggle", function() {
var o = e(this)
.toggleClass("collapsed")
.siblings("ul.json-dict, ol.json-array");
if (o.toggle(), o.is(":visible")) o.siblings(".json-placeholder")
.remove();
else {
var t = o.children("li")
.length,
n = t + (t > 1 ? " items" : " item");
o.after('<a href class="json-placeholder">' + n + "</a>")
}
return !1
}), e(this)
.on("click", "a.json-placeholder", function() {
return e(this)
.siblings("a.json-toggle")
.click(), !1
}), 1 == s.collapsed && e(this)
.find("a.json-toggle")
.click()
})
}
}(jQuery),
function(e) {
function o(e) {
var o = {
'"': '\"',
"\": "\\",
"b": "\b",
"f": "\f",
"n": "\n",
"r": "\r",
" ": "\t"
};
return e.replace(/["\bfnrt]/g, function(e) {
return o[e]
})
}
function t(e) {
if ("string" == typeof e) o(e);
else if ("object" == typeof e)
for (var n in e) e[n] = t(e[n]);
else if (Array.isArray(e))
for (var s = 0; s < e.length; s++) e[s] = t(e[s]);
return e
}
function n(o, t, n) {
n = n || {}, n.editable !== !1 && (n.editable = !0), this.$container = e(o), this.options = n, this.load(t)
}
n.prototype = {
constructor: n,
load: function(e) {
e = t(e), this.$container.jsonViewer(t(e), {
collapsed: this.options.defaultCollapsed,
withQuotes: !0
})
.addClass("json-editor-blackbord")
},
get: function() {
try {
return e(".collapsed").click(), JSON.parse(this.$container.text())
} catch (o) {
alert("Wrong JSON Format: " + o)
}
}
}, window.JsonEditor = n
}(jQuery);
</script>
<div id="json-container"></div>
<script>
// Load and display JSON data
var jsonData = {
"mtlsRootUrl": "https://people.mtls.googleapis.com/",
"auth": {
"oauth2": {
"scopes": {
"https://www.googleapis.com/auth/contacts": {
"description": "See, edit, download, and permanently delete your contacts"
},
"https://www.googleapis.com/auth/contacts.other.readonly": {
"description": "See and download contact info automatically saved in your "Other contacts""
},
"https://www.googleapis.com/auth/contacts.readonly": {
"description": "See and download your contacts"
},
"https://www.googleapis.com/auth/directory.readonly": {
"description": "See and download your organization's GSuite directory"
},
"https://www.googleapis.com/auth/user.addresses.read": {
"description": "View your street addresses"
},
"https://www.googleapis.com/auth/user.birthday.read": {
"description": "See and download your exact date of birth"
},
"https://www.googleapis.com/auth/user.emails.read": {
"description": "See and download all of your Google Account email addresses"
},
"https://www.googleapis.com/auth/user.gender.read": {
"description": "See your gender"
},
"https://www.googleapis.com/auth/user.organization.read": {
"description": "See your education, work history and org info"
},
"https://www.googleapis.com/auth/user.phonenumbers.read": {
"description": "See and download your personal phone numbers"
},
"https://www.googleapis.com/auth/userinfo.email": {
"description": "See your primary Google Account email address"
},
"https://www.googleapis.com/auth/userinfo.profile": {
"description": "See your personal info, including any personal info you've made publicly available"
}
}
}
},
"servicePath": "",
"description": "Provides access to information about profiles and contacts."
};
var jsonEditor = new JsonEditor("#json-container");
jsonEditor.load(jsonData);
function downloadSection(link) {
const section = link.closest('li').find('ul.json-dict, ol.json-array');
const sectionData = section.jsonViewer('get');
// Convert the JSON data to a JSON string
const jsonString = JSON.stringify(sectionData, null, 2);
// Create a Blob with the JSON data
const blob = new Blob([jsonString], {
type: 'application/json'
});
// Create a URL for the Blob
const url = URL.createObjectURL(blob);
// Create a link to trigger the download
const a = document.createElement('a');
a.href = url;
a.download = 'json_section.json';
// Trigger the click event on the link
a.click();
// Revoke the URL to free up resources
URL.revokeObjectURL(url);
}
function setupDropdownMenus() {
$('.json-toggle').each(function() {
const dropdown = $('<div class="dropdown"></div>');
$(this).after(dropdown);
const dropdownToggle = $('<a class="btn btn-secondary dropdown-toggle" data-bs-toggle="dropdown" aria-expanded="false">Download</a>');
dropdown.append(dropdownToggle);
const dropdownMenu = $('<ul class="dropdown-menu"></ul>');
dropdown.append(dropdownMenu);
dropdownMenu.append('<li><a class="dropdown-item" href="#" onclick="downloadSection($(this));">Download Section</a></li>');
});
}
setupDropdownMenus();
</script>
</body>
</html>
2
Answers
You appear to be attempting to construct a JSON reader with a download function for certain chunks of JSON data. The problem you’re seeing might be due to how you’re using the
downloadSection
function in your HTML and JavaScript code.You appear to be attempting to invoke the
downloadSection
function with the input$(this)
. However, because it is not a DOM element,$(this)
is not an acceptable parameter for the method. You should supply the DOM element on which you wish to operate, and then use JavaScript to go to the appropriate area.In your JavaScript code, you should modify the
downloadSection
function to accept the DOM element as an argument. Then, you can use jQuery to navigate to the correct section:whenever you want to download a JSON file, you can use the download attribute on an tag. You can add click event listener to your dropdown and set the href and download attributes of the tag to the current JSON data. I hope below example could solve your problem