How to render a JSON template using mustache - json

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

Related

Nest a Json in Speech Marks

I have a JSON that I'd like to nest into another JSON. Is this possible? Problem I'm facing is when I add Json #2 to #1 is gives me a formatting error.
JSON #1:
{"home":"This a sentence about home", "json":"<ADD JSON HERE>"}
JSON #2:
{
"homepage": {
"heading": [
{"h1":"Sentence for H1!"},
{"description":"Description about us"},
{"button1":"Learn More"},
],
}
What I've tried:
{"home":"This a sentence about home", "json":" { "homepage": {"heading": [ {"h1":"Sentence for H1!"},{"description":"Description about us"},{"button1":"Learn More"},],}"}
(If you are using JavaScript)
If you pass JSON to JSON.stringify it will escape your JSON.
You can then insert the escaped JSON in to your original JSON.
So:
const jsonToInsert = {
"homepage": {
"heading": [
{"h1":"Sentence for H1!"},
{"description":"Description about us"},
{"button1":"Learn More"}
]
}
};
const stringifiedJson = JSON.stringify(jsonToInsert);
const completeJson = {"home":"This a sentence about home", "json": stringifiedJson}
Should work - sorry if there’s typos, replying on my phone.
The second JSON isn't valid (extra commas and missing }), but this is:
{
"homepage": {
"heading": [
{"h1":"Sentence for H1!"},
{"description":"Description about us"},
{"button1":"Learn More"}
]
}
}
To embed it as a string, backslash-escape the embedded double-quotes:
{
"home": "This a sentence about home",
"json": "{\"homepage\": {\"heading\": [{\"h1\": \"Sentence for H1!\"}, {\"description\": \"Description about us\"}, {\"button1\": \"Learn More\"}]}}"
}

Having a problem with iterating over multiple json objects and showing them in div with vue.js

Trying to create a website that takes in information from an API, however I don't really understand how to do it seeing that I need all results grouped up and the API I've created almost never gives a response with the same amounts of objects. So the question is, seeing that I use vue.js and axios is there any way to loop through the json objects to show each of the objects in a seperate ? I manage to do it when there are a specified amounts, but I want to make it dynamic so I don't hardcode into the variables what part of the response I need to set to each variable.
UPDATE: I've tried to use v-for, but seeing that I need to have the output quite structured it doesn't really help, I've also tried Nested V-for loops, once again I can't get the accuracy that I'm looking for.
UPDATE2: Also should be added, when I say JSON object I actually ment js object. the json.parse() has been used on the json.
UPDATE3: Updated the JSON to actual data that I'm using for the application.
Every div need a lemma, a paradigm tagset, inflection tagset and inflectionForms and a table for all the meanings. Just need meaning not meaningText. TranslationId is not important. The JTranslate that wraps every object will be removed, just kinda tired of the Java at the moment, will do that later today and do the adjustments on the vue projects aswell regarding that deletion.
Actually your json format is invalid
{
"object1":{
"name": "test",
"data": "test"
},
"object2":{
"name": "test2",
"data": "test2"
},
"object3":{
"name": "test2",
"data": "test2"
}
}
it should be like above and use JSON.parse() method to simply convert the json to javascript object
Valid Object:
var objects = {
"object1":{
"name": "test",
"data": "test"
},
"object2":{
"name": "test2",
"data": "test2"
},
"object3":{
"name": "test2",
"data": "test2"
}
}
for iteration use
<div v-for="(object,index) in objects" :key="index">
{{object}}
</div>
The correct object as an array:
test: [
{
object1: {
name: 'name1',
data: 'content1'
}
},
{
object2: {
name: 'name1',
data: 'content1'
}
},
{
object3: {
name: 'name3',
data: 'content3'
}
}
]
can be mapped as a computed property inside the script tages:
computed: {
mappedTest() {
return this.test.map(entry => {
const key = Object.keys(entry)[0];
return { name: entry[key].name, data: entry[key].data };
});
}
},
and call it inside the template
<div
v-for="testObject in mappedTest"
:key="testObject"
>
name: {{testObject.name}}; data: {{testObject.data}}
</div>
I was very tired when I asked this question, apparently I did everything wrong. Can easily be solved by nested v-for loops.

search in elastic search index created using a json file

I pushed a json file ( as shown below ) to ES using the following code :
with open('test.json','rb') as payload:
headers = {'content-type': 'application/json'}
r = requests.post('http://localhost:9200/test_nest_json/1',data=payload, verify=False, headers=headers)
{
"data": [
{
"keyword": "abc",
"lists": [
{
"item_val": "some_val"
}
],
"another_key": "some_key"
},
{
"keyword": "xyz",
"lists": [
{
"item_val":"another_val"
}
],
"another_key": "pqr"
}
]
}
I tried updating the mappings and used the term query but still it results in displaying all the indices. I am not able to query only one keyword like "data.keyword" = "abc" using term query.
Looks like you are having a problem with nested object
https://www.elastic.co/guide/en/elasticsearch/guide/current/nested-objects.html
The reason for this cross-object matching, as discussed in Arrays of
Inner Objects, is that our beautifully structured JSON document is
flattened into a simple key-value format in the index
So the effective document stored looks like this:
{
"data.keyword": [ abc, xyz ],
"data.another_key": [ some_key, pqr ],
}
Which means the query you posted will match any document, as long as at least one of the nested object contains the xyz keyword. I recommend reading the link above for clarification.
This is what worked for me :
es.indices.refresh(index="test-index")
with open('abc.json','rb') as payload:
json_data = json.load(payload);
leng = len(json_data["data"])
for i in range (leng):
doc = json.dumps(json_data["data"][i]);
res = es.index(index="sample-index", doc_type='pdf',id=str(uuid.uuid4()), body=doc)
I am parsing the json and extracting the array items one by one and push it to ElasticSearch.
{
"keyword": "abc",
"lists": [
{
"item_val": "some_val"
}
],
"another_key": "some_key"
},
Still looking for an optimised solution.

Removing excess comma on JSON Object

Currently been working on eliminating the excess "," comma on the json object I have below.
{"rules": {
"1000": {
"action": "2",
"category": "skype",
"entity": "Private",
"id": "1000",
},
"1200": {
"action": "2",
"category": "http",
"entity": "Public",
"id": "1200",
},
"100": {
"action": "2",
"category": "ftp",
"entity": "Public",
"id": "100",
},
"0": {
"entity": "Private",
"category": "alcohol, tobacco",
"action": "1",
"id": "low",
},
"3000": {
} }}
Maybe you have some insights on what's the cleanest way to eliminate it using AngularJS.
The data was parsed from this code snippet.
var request = {
url: 'sample/uri',
method: "GET",
transformResponse: specialTransform
};
var response = $q.defer( );
$http( request ).success( function( THIS DATA -> data, status ) {
eval
var fixTrailingCommas = function (jsonString) {
var jsonObj;
eval('jsonObj = ' + jsonString);
return JSON.stringify(jsonObj);
};
fixTrailingCommas('{"rules": { "1000": { "action": "2", "category": "skype", "entity": "Private", "id": "1000" , } } }');
Please use eval here only if you completely trust incoming json, and also be aware of other eval evils as described on MDN and its note on JSON parsing
Note that since JSON syntax is limited compared to JavaScript syntax, many valid JavaScript literals will not parse as JSON. For example, trailing commas are not allowed in JSON, and property names (keys) in object literals must be enclosed in quotes. Be sure to use a JSON serializer to generate strings that will be later parsed as JSON.
You may also choose to rely on implementation of JSON2 by Douglas Crockford which uses eval internally
On current browsers, this file does nothing,
preferring the built-in JSON object. There is no reason to use this file unless
fate compels you to support IE8, which is something that no one should ever
have to do again.
But because we really need to use this library, we have to make few code modifications, e.g. simply comment out JSON type check, which will then override native browser object (or we may also introduce new JSON2 global variable)
//if (typeof JSON !== 'object') {
JSON = {};
//}
P.S. Other parsing fuctions json_parse.js and json_parse_state.js, which don't use eval, throw a syntax error
Angular part
var config = {
transformResponse: function (data, headers) {
if(headers("content-type") === "application/json" && angular.isString(data)) {
try {
data = JSON.parse(data);
} catch (e) {
// if parsing error, try another parser
// or just fix commas, if you know for sure that the problem is in commas
data = JSON2.parse(data);
}
return data;
} else {
return data;
}
}
};
$http.get("rules.json", config).success(function (data) {
$scope.rules = data;
});
So as you said, the JSON is wrongly generated on the server you are taking it from, can you change the way it is generated there? (Follow this: Can you use a trailing comma in a JSON object?)
In case you are unable to do so, you need to use something like mentioned here:
Can json.loads ignore trailing commas?
library to repair a JSON object, like: https://www.npmjs.com/package/jsonrepair
(try some online fix tool here: http://www.javascriptformat.com/)
or some regexp magic

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