How to format json file view on html - html

current json view on html page
{"result": [{"id": "103300640", "sms_phone": "730276061", "corrected to":
"27730276061"}, {"id": "103277733", "sms_phone": "716125197", "corrected
to": "27716125197"}]}
what I want it to be formatted display like
{
"result":[
{
"id":"103300640",
"sms_phone":"730276061",
"corrected to":"27730276061"
},
{
"id":"103277733",
"sms_phone":"716125197",
"corrected to":"27716125197"
}]
}
JS code:
#app.route('/<path:req_path>')
def dir_listing(req_path):
abs_path = os.path.join(UPLOAD_FOLDER, req_path)
# Check if path is a file and serve
if os.path.isfile(abs_path):
return send_file(abs_path, mimetype="application/json")
return render_template('/index.html')
HTML code:
<ul>
{% for file in file_list %}
<li>{{ file }}</li>
{% endfor %}
</ul>

You can try this out:
Use <pre> tag for showing code itself in HTML page and with JSON.stringify().
var data = {"result": [{"id": "103300640", "sms_phone": "730276061", "corrected to": "27730276061"}, {"id": "103277733", "sms_phone": "716125197", "corrected to": "27716125197"}]}
document.getElementById("beautified").innerHTML = JSON.stringify(data, undefined, 2);
<pre id="beautified"></pre>
The JSON.stringify() method converts a JavaScript object or value to a JSON string, optionally replacing values if a re-placer function is specified or optionally including only the specified properties if a re-placer array is specified.

You have to use JS to achieve this.
Please have a look at the below code.
Use the <pre> tag to achieve this.
<html>
<head>
</head>
<body onload="myFunction()">
<script>
function myFunction() {
var data = {
"data": {
"x": "1",
"y": "1",
"url": "http://test.com"
},
"event": "start",
"show": 1,
"id": 50
}
document.getElementById("json").innerHTML = JSON.stringify(data, undefined, 2);
}
</script>
<pre id="json"></pre>
</body>
<html>

You can use JSON.stringify
See example at: https://codepen.io/adrianparr/pen/VeyeVP

Related

Vega statistics Get Transform result as an object

I want to use transform in Vega and get results as an object. Similar to the example in the link:
https://vega.github.io/vega/docs/transforms/aggregate/
I want to get the output, example: [{"v": 2, "s": 6, "m": 2}], and use it in other calculation. So I don't want to load to visualization ex. chart. I want to get the resulted object and work on it. Can I do that.
Here are the steps:
For Vega spec, just include the data block with transforms.
Run Vega the usual way to create a Vega "view".
In javascript, use Vega View API's data method to get the transformed dataset object.
Here is a complete working example (html and javascript) using the example from Vega aggregate.
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-Type" content="text/html;charset=utf-8" />
<title>Test Vega5</title>
</head>
<body>
<div id="vis"></div>
</body>
<script src="https://vega.github.io/vega/vega.js"></script>
<script>
let vegaSpec = {
"$schema": "https://vega.github.io/schema/vega/v5.json",
"data": [
{
"name": "mydata",
"values" : [
{"foo": 1, "bar": 1},
{"foo": 1, "bar": 2},
{"foo": null, "bar": 3}
],
"transform": [
{
"type": "aggregate",
"fields": ["foo", "bar", "bar"],
"ops": ["valid", "sum", "median"],
"as": ["v", "s", "m"]
}
]
}
]
};
let vegaView = new vega.View(vega.parse(vegaSpec))
.logLevel(vega.Warn)
.initialize("#vis")
.renderer("svg")
.hover()
.run();
let my_transformed_data = vegaView.data("mydata"); // vega view API
console.log(my_transformed_data);
</script>
</html>
console.log output:

How to render a JSON template using mustache

I'm trying to generate a JSON file with mustache with the following template:
{
"name": "{{customer_info.first_name}}",
"email": "{{contact_info.email}}",
"campaign": {
"campaignId": "{{contact_info.campaign.campaignId}}"
},
"tags": [
{{#contact_info.tags}}
{
"tagId": "{{tagId}}"
},
{{/contact_info.tags}}
]
}
As an output example I get:
{
"name": "Antonio",
"email": "myemail#gmail.com",
"campaign": {
"campaignId": "pfft"
},
"tags": [
{
"tagId": "6prrtAP"
},
{
"tagId": "64rrrE9"
},
]
}
Which unluckily is a BAD FORMATTED JSON, because there is a not wanted "," after the last element in the array.
Can any of you help me in solving this issue and remove the comma ?
Thanks a lot
Try using SelectTransform npm package. It has Mustache like syntax without all the side-effects that Mustache creates and the package size is also not as heavy as Handlebars.js
import ST from "stjs";
const data = {
name: 'Jakub',
friends: [
{
name: 'Michal'
}
]
};
const template = {
newName: '{{ name }}',
friends: {
'{{ #each friends }}': {
subName: '{{ name }}'
}
}
};
console.log(ST.select(data).transformWith(template).root());
// Result:
/**
* {
* "newName": "Jakub",
* "friends": [
* {
* "subName": "Michal"
* }
* ]
* }
*/
I would do this:
var md = {};
var tagsCount = 2;
var currTagIndex = 0;
md['show_comma'] = function(){
currTagIndex++;
return currTagIndex <= tagsCount;
}
Then in Mustache template:
{{#show_comma}}
,
{{/show_comma}}
I've been experiencing some similar problem and I found out that Handlebars is a lot similar to mustache and way more powerful.
You could check that out and try using this template to solve your problem, without adding anything to your current model.
{
"name": "{{customer_info.first_name}}",
"email": "{{contact_info.email}}",
"campaign": {
"campaignId": "{{contact_info.campaign.campaignId}}"
},
"tags": [
{{#each contact_info.tags}}
{
"tagId": "{{tagId}}"
}{{#unless #last}},{{/unless}}
{{/each}}
]
}
Don't generate JSON from textual templates. You'll constantly face problems like this. Superfluous commas, meta characters in strings (what if customer_info.first_name contains double quotes), failing to properly nest structures etc.
Generate your data as native structures in your programming language, and encode it as JSON using library provided by your programming language.
However, if you absolutely need, try to generate as much JSON data as possible (ideally, self-contained JSON fragment) outside template, and interpolate that inside template. For example:
let contact_info = {"tags": [ "6prrtAP", "64rrrE9" ]}
let tags = contact_info.tags.map((tag) => ({"tagId": tag})); // [{tagId: "6prrtAP"}, {tagId: "64rrrE9"}]
let tagsJSON = JSON.stringify(tags); // "[{\"tagId\":\"6prrtAP\"},{\"tagId\":\"64rrrE9\"}]"
Then, pass tagsJSON to your template:
{
"name": "{{customer_info.first_name}}",
"email": "{{contact_info.email}}",
"campaign": {
"campaignId": "{{contact_info.campaign.campaignId}}"
},
"tags": {{tagsJSON}}
}
That way, tagsJSON always contains valid JSON-encoded data, so it might be safely interpolated as a value in JSON dictionary/object. Even if tag list is empty, even if tag IDs suddenly start to contain characters that need escaping etc. All corner cases are already handled for you.
This looks like a good answer:
contact_info['tags'][ contact_info['tags'].length - 1 ].last = true;
and the template would be
{{#contact_info.tags}}
{
"tagId": "{{tagId}}"
} {{^last}}, {{/last}}
{{/contact_info.tags}}
Source: https://stackoverflow.com/a/7591866

How to escape characters for JSON with Javascript

How i can escape characters for JSON with javascript in one page?
Here is js what i need used
bernhardhaeussner.de/odd/json-escape/ (here is text encoding after paste an click on ↓ escape ↓, but i need that text will be encode in load.)
github.com/douglascrockford/JSON-js/blob/ad6079cbd8dc362a3cc42e1f97c01aa5ccd48bfe/json2.js#L211
But i can't imagine how i can make it.
I need global code something like this.
<script>document.write(escape("Test code"));</script>
Give me example please man!:) Here is code what i have
{ "snippet": { "data": "2022-02-15T23:32:01.000Z", "data2": "2022-02-14T23:32:01.000Z", "data3": "t3", "data4": "test descr" }, "data": { "status": "bxx" }}
After escaped code is "{ \"snippet\": { \"data\": \"2022-02-15T23:32:01.000Z\", \"data2\": \"2022-02-14T23:32:01.000Z\", \"data3\": \"t3\", \"data4\": \"test descr\" }, \"data\": { \"status\": \"bxx\" }}"
How i can make it? Give please example with js. Thanks!
You don't have to do any "escaping" for JSON; just create the structure you want to turn into a JSON string, and use JSON.stringify to create the string. I'd give you an example but I can't begin to see from your question what you're trying to turn into JSON.
escape is completely unrelated to JSON (or just about anything else but unescape).
Re your update:
If you have a variable containing that structure, again, just use JSON.stringify on it:
var data = { "snippet": { "data": "2022-02-15T23:32:01.000Z", "data2": "2022-02-14T23:32:01.000Z", "data3": "t3", "data4": "test descr" }, "data": { "status": "bxx" }} ;
var json = JSON.stringify(data);

embed json file within d3.js

http://bl.ocks.org/mbostock/4339083 am using this
instead of d3.json("/d/4063550/flare.json", function(error, flare) {
how do i make it use the json file within the html, like say i have
var jsonData = [{
"name": "A",
"children": [
{"name": "A1", "children": [{"name": "A12"},{"name": "A13"},{"name": "A14"}] },
{"name": "A2", "children": [{"name": "A22"},{"name": "A23"},{"name": "A24"}] }
]
}];
and i want to use this instead of an external json file, how do i achieve this ?
Solution:
1.you can assign the JSON data to variable name then You can build the tree layout
2.use one function to get the JSON data
Fiddle for 1 solution
Fiddle for 2 solution
var root = getData(),
nodes = cluster.nodes(root),
links = cluster.links(nodes);

Using JSON.parse for accessing a json file

jQuery Code:
$(document).ready(function(){
$.getJSON('dat.js', function(data) {
var obj = JSON.parse(data);
alert(obj[0].title);
});
});
My JSON file :
{
"posts":
[
{
"title": "ajax | Programming ",
"url": "hello"
},
{
"title": "jQuery and Ajax Demos Pard - 3",
"url": "how are you"
},
]
}
Its giving me an error JSON.parse:unexpected character. But when I tried to do it by taking the json inside an array its ok then. I want to access the data from json file itself
you do parseJSON when your input is a json string and u expect an object. Here, getJSON is already giving u the response as an object.
try this
$(document).ready(function(){
$.getJSON('dat.js', function(obj) {
alert(obj.posts[0].title);
});
});
A Quick jslint check says that you have invalid json at line 11 },, Try removing the comma from the last member of "posts" and see if that help
{
"title": "jQuery and Ajax Demos Pard - 3",
"url": "how are you"
}, <---- THIS