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\"}]}}"
}
Related
I'm trying to write a webhook in Go for Dialogflow, I'm using the apiv2 of the official SDK
google.golang.org/genproto/googleapis/cloud/dialogflow/v2
But I can't generate a correct response using the official sdk.
What I mean is that following the documentation and the WebhookResponse struct I can't generate the expected json for the response.
This is the piece of code that I'm using:
response = dialogflow.WebhookResponse{
FulfillmentMessages: []*dialogflow.Intent_Message{
{
Message: &dialogflow.Intent_Message_Card_{
Card: &dialogflow.Intent_Message_Card{
Title: "Title",
Subtitle: "Subtitle",
ImageUri: "https://example.com/images/example.png",
Buttons: []*dialogflow.Intent_Message_Card_Button{
{
Text: "Button",
Postback: "https://example.com/path/for/end-user/to/follow",
},
},
},
},
},
},
}
This is the json that it generates:
{
"fulfillment_messages": [
{
"Message": {
"Card": {
"title": "Title",
"subtitle": "Subtitle",
"image_uri": "https://example.com/images/example.png",
"buttons": [
{
"text": "Button",
"postback": "https://example.com/path/for/end-user/to/follow"
}
]
}
}
}
]
}
But this is the json that I should send back (according to the official documentation)
"fulfillmentMessages": [
{
"card": {
"title": "card title",
"subtitle": "card text",
"imageUri": "https://example.com/images/example.png",
"buttons": [
{
"text": "button text",
"postback": "https://example.com/path/for/end-user/to/follow"
}
]
}
}
]
}
So my json doesn't work, because it has the Message that shouldn't be there, and Card with uppercase first letter. I've tried to send the json of the documentation and it works, Dialog Flow responds correctly.
I don't understand how to generate the correct json using the official SDK. Please consider that I'm pretty new using Go Lang. This is my first project.
This is the documentation that I'm using at the moment:
https://pkg.go.dev/google.golang.org/genproto/googleapis/cloud/dialogflow/v2?tab=doc#WebhookResponse
As you can see the FulfillmentMessages is an array of Intent_Message
FulfillmentMessages []*Intent_Message
And the Intent_Message has to contain Message (here the documentation)
Thanks in advance for any help and suggestions.
H2K
UPDATE:
if I use log.Println(response) I can see the correct response inside the log
fulfillment_messages:{card:{title:"Title" subtitle:"Subtitle" image_uri:"https://example.com/images/example.png" buttons:{text:"Button" postback:"https://example.com/path/for/end-user/to/follow"}}}
It is not a JSON but the structure is correct, no Message, no Card...
So the problem is when I return it with Gin and the command:
c.JSON(200, response)
I've found a solution!
I need to use the jsonpb marshaler and return it as string with Gin
Here an example:
m := jsonpb.Marshaler{}
result, _ := m.MarshalToString(response)
c.String(200, result)
I've totally went crazy on it, I hope that it could be helpful for someone else.
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
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 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);
I got problem. I have this JSON automatically generated by Open Flash Chart php library. The problem is, OFC report JSON Parse Error [Syntax Error] while test result using http://www.jsonlint.com/ report that my JSON is fine. But, w3c parser report error too:(
Any help?
Here's the JSON:
{
"title": "Followers Trend",
"elements": [
{
"type": "area_hollow",
"fill-alpha": 0.35,
"values": [
],
"colour": "#5B56B6",
"text": "Followers",
"font-size": 12
}
],
"x_axis": {
"colour": "#A2ACBA",
"grid-colour": "#D7E4A3",
"offset": false,
"steps": 4,
"labels": {
"steps": 2,
"rotate": "vertical",
"colour": "#A2ACBA",
"labels": [
]
}
},
"x_legend": {
"text": "Week Trend (2009-08-17 - 2009-08-24)",
"style": "{font-size: 20px; color: #778877}"
},
"y_axis": {
"min": 0,
"max": 150,
"steps": 30
}
}
A few things I learned while playing with JSON is:
If you have validate the JSON on various JSON validation services and the result is GOOD. But, when you failed to eval it, try to wrap your JSON using ( and ) => ({jsondata})
var json = eval( "(" + jsonString + ")" );
NEVER build the JSON yourself. It's a gate to failure. Always use official or popular JSON library (depending on your language). For example:
On PHP: use json_encode()
On Java Android: use org.json.JSONObject
A list of all other available library to play with JSON is listed in JSON official page.
To display and format JSON data, you can use JSONViewer.
I think the w3c parser is having issues, I couldn't even get it to parse this:
{
"title" : "Followers Trend"
}
It gave me this error:
Validation errors:
lexer couldn't parse at "{
"title" : "Followers Trend"
}"
http://json.bloople.net helps you visualise the code to find and correct errors.
try this code, JSON.parse() method is not able to handle string which is in a
single quote as a value in the right-hand side. also if you want to handle the
UTF-8 character code, then it will do.
parseJSON = function() {
var data = {};
var reader = new FileReader();
reader.onload = function() {
try {
data = JSON.parse(reader.result.replace(/'/g, "\""));
console.log(data)
} catch (ex) {
console.log('error' + ex);
}
};
reader.readAsText(fileSelector_test[0].files[0], 'utf-8');
}