I would like to pretty print JSON on a web page and highlight some text / lines in it.
Ideally I am searching for a IFRAME - service to which I can link and URL where the JSON get's donwloaded and displayed as HTML, but I would like to specify an search string, which should be highlighted or the whole line containing the search string should be highlighted. The JSON is public so there is no privacy issue.
If there is no such service, is there a Javscript library which supports highlighting?
Focusing in more on your question about iframes - it's an issue in itself. It's not possible to do what you want in an iframe if the domain names aren't the same. However there are some workarounds for the same-origin policy that could help you in this situation.
Ideally the service you're pulling from supports jsonp so you don't have to deal with iframes and can do what you like with the json response without worrying about the same-origin policy.
As mentioned in a previous answer of mine you can use Prettify to apply syntax highlighting, though you can't highlight a specific line (from what I've found so far). For this example I'll be using the GitHub API.
For the HTML, you would have:
<pre id="jsonCode" class="prettyprint lang-json"></pre>
And the JavaScript to fetch and pretty print the JSON response (switch out jquery if you'd like):
$.getJSON('https://api.github.com/users/trevorsenior?callback=?',
function(data) {
var jsonString = JSON.stringify(data, null, 4);
$('#jsonCode').text(jsonString);
prettyPrint(); //apply syntax highlighting to to JSON
});
You can look at a working demonstration here: http://plnkr.co/edit/RiDtloVflmfuOrAokNXE?p=preview
If you do decide to use Prettify take a look at their getting started guide.
Update
To fully answer your question, it is easy enough to add in highlighting to some text by wrapping the text in <span> tags with a specified class. I've thrown together another example of this that builds off of the previous one: http://plnkr.co/edit/FM6Ua4pOvMW7nFFggdBy?p=preview
In a nutshell:
.highlighted {
background-color: #ff0;
}
$('#search').keyup(function() {
var search = $('#search').val();
if(jsonString.match(search)) {
var regex = new RegExp(search, 'g');
var highlighted = '<span class="highlighted">' + search + '</span>';
var newJsonString = jsonString.replace(regex, highlighted);
$('#jsonCode').html(prettyPrintOne(newJsonString));
} else {
$('#jsonCode').html(prettyPrintOne(jsonString));
}
});
If you want to remove the dynamic functionality & highlight on load simply move the logic out from the event listener:
var highlight = function(jsonString, searchFor) {
var regex = new RegExp(searchFor, 'g');
var highlighted = '<span class="highlighted">' + searchFor + '</span>';
var newJsonString = jsonString.replace(regex, highlighted);
return prettyPrintOne(newJsonString);
};
And call it just before you populate the area with the code
$('#jsonCode').html(highlight(jsonString, 'X-RateLimit'));
Demonstration: http://plnkr.co/edit/be3SNq1TzeiPKXohXOk9?p=preview
Related
I'm making a simple step-by-step wizard for my website which asked viewers questions about their custom order. I've been using JavaScript to replace the content of each "page" with the document.getElementById('element-id').innerHTML command; however, it seems really slow and awkward to add entire divs as a string. For example, some of the code looks something like this:
function loadNextStep() {
document.getElementById('content').innerHTML = 'This is some content.<br>It seems like I need to write everything in one line to make the command work properly.<br><input type="date" id="date-picker" value=""></input>'
}
I'd love to be able to write some multi-line html code, and say "replace everything with this new html."
Is there a faster way of doing the same thing?
Thank you again!
I don't think getElementById or querySelector will make any difference, since the heavier stuff is done when you add a bunch of html elements as a string despite the fact that innerHTML can be vulnerable to cross site scripting if the output of that string has user input commands in it.
But if you still want to do this way you can do by using `` backticks to add as many lines as you'd like.
However, the way I would do is to create those elements on a different function and then output them to your loadNextStep function, then adding to your #content element using the appendChild method.
Here's a quick example of I would do:
function loadNextStep() {
var content = document.getElementById('content');
var step = step1();
step.forEach( stepContent => {
content.appendChild( stepContent );
})
}
function step1() {
var someContent = document.createElement('span');
someContent.innerText = `This is some content. It seems like I need to write everything in one line to make the command work properly.
Yes, but if you use backticks you can have multiple lines.`;
var input = document.createElement('input');
input.type = 'date';
input.id = 'date-picker';
return [ someContent, input ]
}
loadNextStep();
<div id="content">
</div>
I have made a small code generator for my team
It's very simple, you just fill out the fields & it effectively does a find and replace in the DIV below and shows what the new code should be. That's great!
The problem I have is that in order to get the code showing as clear text on the screen, I had to replace all the special characters with the below (e.g. <)
When manually copying and pasting, this is not a problem. However, I have a button that copies the contents of the DIV and exports to a .html file.
This then does not execute the code, because it copies the actual contents (including the lack of special characters).
Is there any way to get this code to run when I export? Is there a simple function to switch it back to be the original code before exporting?
The code generator is effectively lots of finds and replaces to enter user defined variables, it is below:
[code]function findMyText2(needle2, replacement2) {
if (haystackText.length == 0) {
haystackText = document.getElementById("haystack").innerHTML;
}
var match = new RegExp(needle2, "ig");
var replaced = "";
if (replacement2.length > 0) {
replaced = haystackText.replace(match, replacement2);
}
else {
var boldText = "<div style=\"background-color: yellow; display: inline; font-weight: bold;\">" + needle2 + "</div>";
replaced = haystackText.replace(match, boldText);
}
document.getElementById("haystack").innerHTML = replaced;
haystackText = document.getElementById("haystack").innerHTML;
The full code to be edited is:
Thank you in advance.
From what I understood of the problem, you basically need to unescape the contents of the div. Here is how you can do it.
HTML
<div style="display:none" id="dummy"></div>
JQuery
var decoded = $("#dummy").html(encoded).text();
This code sets the internal HTML of the "dummy" div as encoded, which makes jquery decode it. Then text() simply returns the decoded code.
For more info see here - Javascript decoding html entities
I'm trying make my own html text editor. Like you see picture. I wrote bold, italic, there is no problem.
But when i wrote code (like html code), like you see only write "Test", But I wrote in textarea <p>Test</p>
And I'm using SyntaxHighlighter plugin for display my codes.
And you see my code below
function Textarea(input, preview) {
var text = input.val().replace(/\[b\]/g, "<b>").replace(/\[\/b\]/g, "</b>")
.replace(/\[i\]/g, "<i>").replace(/\[\/i\]/g, "</i>")
.replace(/\[u\]/g, "<u>").replace(/\[\/u\]/g, "</u>")
.replace(/\[s\]/g, "<s>").replace(/\[\/s\]/g, "</s>")
.replace(/\[img\]/g, "<br/><p></p><img src='").replace(/\[\/img\]/g, "' /><br/><p></p>")
.replace(/\[link/g, "<a").replace(/URL="/g, "href='").replace(/"\]/g, "'>").replace(/\[\/link\]/g, "</a>")
.replace(/\[code/g, "<pre").replace(/type="/g, "class='brush:").replace(/"\]/g, "'>").replace(/\[\/code\]/g, "</pre>");
preview.html(text);
}
I know it cause for preview.html(text), I need also write like preview.text(text) code.
But I dont know, how can i do this?
Thanks.
a quick way is to create a element inject the html code as text, then get it back out as html, then the tags, and other characters, should then be in entity form, eg < as < etc
$('<div></div>').text(input.val()).html().replace...
But there are some issues with it, eg whitespaces maybe removed
Because of that this answer shows creating a function that you can use to encode characters, which just encodes the <,>,",',& characters. You could add other characters to the replace to extend the function.
So what you need to do is html encode the raw text given by the user, then replace the bracket entities with html, and finally set the html of the output div. Here's a simple example of that:
http://jsfiddle.net/2K97x/
String.prototype.htmlEncode = function () {
return $('<div/>').text(this).html();
};
function replaceEntities(value) {
return value.replace(/\[b\]/g, "<b>").replace(/\[\/b\]/g, "</b>")
.replace(/\[i\]/g, "<i>").replace(/\[\/i\]/g, "</i>")
.replace(/\[u\]/g, "<u>").replace(/\[\/u\]/g, "</u>")
.replace(/\[s\]/g, "<s>").replace(/\[\/s\]/g, "</s>")
.replace(/\[img\]/g, "<br/><p></p><img src='").replace(/\[\/img\]/g, "' /><br/><p></p>")
.replace(/\[link/g, "<a").replace(/URL="/g, "href='").replace(/"\]/g, "'>").replace(/\[\/link\]/g, "</a>")
.replace(/\[code/g, "<pre").replace(/type="/g, "class='brush:").replace(/"\]/g, "'>").replace(/\[\/code\]/g, "</pre>");
}
var rawValue = $('input').val();
var htmlEncoded = rawValue.htmlEncode();
var newHtml = replaceEntities(htmlEncoded);
$('div').html(newHtml);
This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
JSON pretty print using JavaScript
I'd like to display my raw JSON data on a HTML page just as JSONview does. For example, my raw json data is:
{
"hey":"guy",
"anumber":243,
"anobject":{
"whoa":"nuts",
"anarray":[
1,
2,
"thr<h1>ee"
],
"more":"stuff"
},
"awesome":true,
"bogus":false,
"meaning":null,
"japanese":"明日がある。",
"link":"http://jsonview.com",
"notLink":"http://jsonview.com is great"
}
It comes from http://jsonview.com/, and what I want to achieve is like http://jsonview.com/example.json if you use Chrome and have installed the JSONView plugin.
I've tried but failed to understand how it works. I'd like to use a JS script (CSS to highlight) to custom format my raw JSON data which is retrieved by ajax and finally put it on a HTML page in any position like into a div element. Are there any existing JS libraries that can achieve this? Or how to do it?
I think all you need to display the data on an HTML page is JSON.stringify.
For example, if your JSON is stored like this:
var jsonVar = {
text: "example",
number: 1
};
Then you need only do this to convert it to a string:
var jsonStr = JSON.stringify(jsonVar);
And then you can insert into your HTML directly, for example:
document.body.innerHTML = jsonStr;
Of course you will probably want to replace body with some other element via getElementById.
As for the CSS part of your question, you could use RegExp to manipulate the stringified object before you put it into the DOM. For example, this code (also on JSFiddle for demonstration purposes) should take care of indenting of curly braces.
var jsonVar = {
text: "example",
number: 1,
obj: {
"more text": "another example"
},
obj2: {
"yet more text": "yet another example"
}
}, // THE RAW OBJECT
jsonStr = JSON.stringify(jsonVar), // THE OBJECT STRINGIFIED
regeStr = '', // A EMPTY STRING TO EVENTUALLY HOLD THE FORMATTED STRINGIFIED OBJECT
f = {
brace: 0
}; // AN OBJECT FOR TRACKING INCREMENTS/DECREMENTS,
// IN PARTICULAR CURLY BRACES (OTHER PROPERTIES COULD BE ADDED)
regeStr = jsonStr.replace(/({|}[,]*|[^{}:]+:[^{}:,]*[,{]*)/g, function (m, p1) {
var rtnFn = function() {
return '<div style="text-indent: ' + (f['brace'] * 20) + 'px;">' + p1 + '</div>';
},
rtnStr = 0;
if (p1.lastIndexOf('{') === (p1.length - 1)) {
rtnStr = rtnFn();
f['brace'] += 1;
} else if (p1.indexOf('}') === 0) {
f['brace'] -= 1;
rtnStr = rtnFn();
} else {
rtnStr = rtnFn();
}
return rtnStr;
});
document.body.innerHTML += regeStr; // appends the result to the body of the HTML document
This code simply looks for sections of the object within the string and separates them into divs (though you could change the HTML part of that). Every time it encounters a curly brace, however, it increments or decrements the indentation depending on whether it's an opening brace or a closing (behaviour similar to the space argument of 'JSON.stringify'). But you could this as a basis for different types of formatting.
Note that the link you provided does is not an HTML page, but rather a JSON document. The formatting is done by the browser.
You have to decide if:
You want to show the raw JSON (not an HTML page), as in your example
Show an HTML page with formatted JSON
If you want 1., just tell your application to render a response body with the JSON, set the MIME type (application/json), etc.
In this case, formatting is dealt by the browser (and/or browser plugins)
If 2., it's a matter of rendering a simple minimal HTML page with the JSON where you can highlight it in several ways:
server-side, depending on your stack. There are solutions for almost every language
client-side with Javascript highlight libraries.
If you give more details about your stack, it's easier to provide examples or resources.
EDIT: For client side JS highlighting you can try higlight.js, for instance.
JSON in any HTML tag except <script> tag would be a mere text. Thus it's like you add a story to your HTML page.
However, about formatting, that's another matter. I guess you should change the title of your question.
Take a look at this question. Also see this page.
I have an html table that is being rendered on a web page that I using in a jquery lookup to plug values into textarea.
The table that is rendered on has <td>s with data like this
<td class="ms-vb"><p>Hello. </p><p> line2</p>
and
<div>1</div><div>2</div><div>3</div>
which appears like this on the page.
Hello
line 2
and
1
2
3
I'm using some jquery to pull that data of the hmtl table and insert it into a textarea textbox.. but when I do I'm just see a long string of text without the html tags and certainly no line feeds.
What's a good jquery or javascript way to insert that data into my textearea field that at least linefeeds are preserved in the textarea?
So basically I need a function that would turn this string
Any way in jquery or javascript for form that html data so that at least line feeds are preserved in my multiline textarea?
=== full code here.. basically doing a lookup of some table on my page and using it to plug in values in a two textxboxs:
<script type="text/javascript">
$('select[title$=Issue Type] option:eq(0)').text("Please Select").val("");
$('select[title$=Issue Type]').change(function(){
var issue = $('select[title$=Issue Type] :selected').text();
var bodyprefixes = [];
$('#issuetbl td:contains('+issue+')').nextAll().each(function(i, k) {
bodyprefixes.push($(k).text());
});
$('input[title$=Subject]').val(bodyprefixes[1]);
$('input[title$=Message]').val(bodyprefixes[0]);
});
</script>
Try using regex. If you want to to support other tags, you will have to include them in the regex. The one here supports also:
$('#txtarea').text(
$('td.ms-vb').text()
.replace(/<\/?(br|div|p)\/?>/g, "\n\n")
.replace(/<[^>]+>/g, "")
);
note: you may need to trim quadruple '\n' from your output.
Something like:
var textAreaInput = '';
var getTextFromElement = function() {
textAreaInput += $(this).text() + '\n';
};
$('p').each(getTextFromElement);
$('div').each(getTextFromElement);