How to escape characters for JSON with Javascript - json

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

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\"}]}}"
}

How to remove one property from json input message using replace() expression in azure logic app?

{
"metadata": {
"id": "2",
"uri": "3",
"type": "2"
},
"Number": "2323600002913",
"Date": "04/21/2009",
"postingDate": "00/00/0000",
"ata": {
"results": [
{
"metadata": {
"id": "r",
"uri": "e2",
"type": "s2"
},
"item": "000010",
"data":"ad"
}
]
}
}
want to remove metadata property from above json message and output should be like below
{
"Number": "2323600002913",
"Date": "04/21/2009",
"postingDate": "00/00/0000",
"ata": {
"results": [
{
"item": "000010",
"data":"ad"
}
]
}
}
I tried with removeProperty() which is working for root level metadata but inside metadata not removed.
how to use replace() in this case or anything else to only remove metadata.
The simplest way is use inline code, cause even with removeProperty() expression to remove the metadata under results, it will return the results array data not the whole json data. Then you will have to combine them, it's not a convenient way.
And with inline code you could refer to my below picture. The variable json is the value from triggerbody, then just delete the node or key and return the json variable. And with this way, even you want to delete many metadata in the array, you could add a for loop to delete it, just think of it as plain js code.
Update:if you want to get value from variable,cause no support expression to get value from variable so use the below expression.
var json =wworkflowContext.actions.Initialize_variable.inputs.variables[0].value;
And about how to loop the array in the json refer to my below pic.

Stringify JSON in Logic App

We are sending messages to a service bus using a logic app. These messages will later be consumed by another service, the service expects the message content to be a string - essentially a stringified JSON object, with escape characters.
We are not able to find a method to stringify a JSON object in Logic Apps. Even if we explicitly provide a escaped string the logic app itself detects that it's stringified JSON and unescapes it and then sends it as a JSON object. We don't want that, we simply want it to send the string as it is. We have already tried changing the content type to text/plain, it does not work. The logic app always sends the unescaped string as JSON.
This post on MSDN: https://social.msdn.microsoft.com/Forums/office/en-US/e5dee958-09a7-4784-b1bf-facdd6b8a568/post-json-from-logic-app-how-to-escape-data?forum=azurelogicapps is of no help because doing this will violate the request contract of the message consuming service
Do you need the stringified message to include opening and closing double quotes?
I've tried this and it worked for me.
I have my JSON object as an output of a compose
Then, I initialised a variable with the Base64 encoded value of the escaped stringified JSON (you need to add ALL the proper escaping required,
mine was just a PoC)
Then, you send the variable already in Base64 to Service Bus. (You need to remove the encoding on that action).
"actions": {
"Compose_JSON_Object": {
"inputs": {
"message": "I want this as a string"
},
"runAfter": {},
"type": "Compose"
},
"Initialise_Variable_with_Stringified_JSON_Base64_Encoded": {
"inputs": {
"variables": [
{
"name": "jsonAsStringBase64",
"type": "String",
"value": "#base64(concat('\"', replace(string(outputs('Compose_JSON_Object')), '\"', '\\\"'), '\"'))"
}
]
},
"runAfter": {
"Compose_JSON_Object": [
"Succeeded"
]
},
"type": "InitializeVariable"
},
"Send_message": {
"inputs": {
"body": {
"ContentData": "#variables('jsonAsStringBase64')",
"ContentType": "text/plain"
},
"host": {
"connection": {
"name": "#parameters('$connections')['servicebus']['connectionId']"
}
},
"method": "post",
"path": "/#{encodeURIComponent(encodeURIComponent('temp'))}/messages",
"queries": {
"systemProperties": "None"
}
},
"runAfter": {
"Initialise_Variable_with_Stringified_JSON_Base64_Encoded": [
"Succeeded"
]
},
"type": "ApiConnection"
}
},
This way, I got the message stringified.
HTH

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

Extjs4 How to decode a json code with a json string inside?

I want to decode in extjs4 with Ext.decode(string), a json string with json string inside, just like this:
var string = "{success:true,
rows:[{"jsonfields":"[
{\\"name\\":\\"cm:title\\",\\"title\\":\\"Titolo\\",\\"description\\":\\"Titolo del contenuto\\",\\"dataType\\":\\"d:mltext\\",\\"url\\":\\"\/api\/property\/cm_title\\"},
{\\"name\\":\\"cm:content\\",\\"title\\":\\"Contenuto\\",\\"description\\":\\"Contenuto\\",\\"dataType\\":\\"d:content\\",\\"url\\":\\"\/api\/property\/cm_content\\"},
{\\"name\\":\\"cm:name\\",\\"title\\":\\"Nome\\",\\"description\\":\\"Nome\\",\\"dataType\\":\\"d:text\\",\\"url\\":\\"\/api\/property\/cm_name\\"}]"}
]}";
As you can see "jsonfields" is a json string code.
How I can decode this string with Ext.decode(string)
Any suggests?
There were a couple of problems with your JSON code.
All of your keys needed to be in quotes (success and rows were not).
Use single quotes when embedding a JSON string directly into javascript. This way you can avoid using the escape character.
Below is the correct JSON code. I have also updated your jsfiddle link.
var string = '{
"success": true,
"rows": [
{
"jsonfields": [
{
"name": "cm: title",
"title": "Titolo",
"description": "Titolodelcontenuto",
"dataType": "d: mltext",
"url": "/api/property/cm_title"
},
{
"name": "cm: content",
"title": "Contenuto",
"description": "Contenuto",
"dataType": "d: content",
"url": "/api/property/cm_content"
},
{
"name": "cm: name",
"title": "Nome",
"description": "Nome",
"dataType": "d: text",
"url": "/api/property/cm_name"
}
]
}
]}';
var decodedString = Ext.decode(string);
console.log(decodedString);
​
That's the correct way to decode JSON with Ext and the exception is likely telling you about some invalid syntax in your JSON string. The JSON format is very strict.
You can use an online validator like jsonlint to help figure out what's wrong with your syntax.
One other note: in cases like this, it's usually easier to use single quotes around your string so that you can embed double-quotes without having to escape them.
var string = '{ "success": true, ...}'