Formatting JSON for email body - javascript

I've JSON in the following format that I'm trying to insert into outlook/email client's body using
location.href = "mailto:" + "email#domain.com" + "?subject=" + "Notes" + "&body=" + JSON.stringify(data, null, 4);
Giving 4 spaces JSON.stringify(data, null, 4)
[
{
"page": "article_0_page_0",
"note": "Note 1"
},
{
"page": "article_0_page_1",
"note": "Note 2"
}
]
I want to output as
<b>article_0_page_0</b>\n\r
Note 1
<b>article_0_page_1</b>\n\r
Note 2
Any regular expression solution please.
Edit: My attempt
var str = "";
for(var i=0; i<data.length; i++) {
str += "<strong>" + data[i].page + "</strong><br>" + data[i].note + "<br><br>";
}

I think the above answer is ok if you have a flat structure.
If you want a more holistic approach for email specifically, I have found this to work really well.
const data = {...}
JSON.stringify( data, null, ' ' ).split( '\n' ).join( '<br>' );
This will convert something like this
const json = {
"status": "ok",
"config": {
"gotIt": "yes",
"transform": [
null
]
}
}
Into something like this
{<br>&nbsp"status": "ok",<br>&nbsp"config": {<br>&nbsp&nbsp"gotIt": "yes",<br>&nbsp&nbsp"transform": [<br>&nbsp&nbsp&nbspnull<br>&nbsp&nbsp]<br>&nbsp}<br>}
Email clients will render this as the following
{
"status": "ok",
"config": {
"gotIt": "yes",
"transform": [
null
]
}
}
This is done by using the additional parameters in JSON.stringify which I don't see used very often if you want to read more about these parameters here is the link for them.

Here ya go
var json = [
{
"page": "article_0_page_0",
"note": "Note 1"
},
{
"page": "article_0_page_1",
"note": "Note 2"
}
];
var out = "";
for (var key in json) {
if (json.hasOwnProperty(key)) {
out += "<b>"+json[key].page+"</b>\r\n"+json[key].note+"\r\n\r\n";
}
}
console.log(out);
Example Here: https://jsfiddle.net/q5r4gdcn/1/

This is what I used to convert basic JSON to "readable" for email:
let json = {
"key": "asdas",
"query": "",
"hints": {
"nested1": "blahblah"
}
}
let prettyJSON = JSON.stringify(json, null, ' ')
.split('\n')
.join('<br> ')
.split('<br> }').join('<br>}')
document.body.innerHTML += `<div>${prettyJSON}</div>`

Related

Unable to parse JSON filename object

I am unable to parse a JSON object (whatever.png) for some reason, I get [object%20Object] which is strange as I never have this issue, as its clearly simple to resolve or stringify and debug if in doubt.
My jQuery code:
$(function () {});
$.ajax({
url: '/shouts/get/ajax',
method: 'GET',
dataType: 'JSON',
success: function (res) {
res.forEach((element, i) => {
data = {
message: element['message'],
date: element['date'],
descr: element['descr'],
last_login: element['last_login'],
added: element['added'],
user: element['user'],
username: element['username'],
user_id: element['user_id'],
avatar: element['avatar'],
badges: element.badges
}
var result = XBBCODE.process({
text: data.message,
removeMisalignedTags: false,
addInLineBreaks: false
});
let allstring = '<div class="shoutbox-container"><span class="shoutDate" style="width:95px">' + jQuery.timeago(data.date) + ' <span style="color:#b3b3b3">ago</span><span id="user_badge_' + i + '"></span></span><span class="shoutUser"><a class="tooltip-shoutuser" title="' + data.username + '" href="/user/?id=' + data.user_id + '"><img src="' + data.avatar + '" class="shout-avatar" /></a></span><span class="shoutText">' + result.html + '</span></div><br>';
document.getElementById('shoutbox').innerHTML += allstring;
let badges = [];
data.badges.forEach(badge => {
badges.push('<img src="/images/avatars_gear/' + badge + '">').innerHTML += badges; // <--- Object bug
});
badges.forEach(badge => {
document.getElementById('user_badge_' + i).innerHTML += badge;
});
});
$('.shoutbox-container').filter(function () {
return $(this).children().length === 3;
}).filter(':odd').addClass('shoutbox_alt');
$('.shoutbox-container').each(function () {
$(this).parent().nextAll().slice(0, this.rowSpan - 1).addClass('shoutbox_alt');
});
$('.tooltip-shoutuser').tooltipster({
animation: 'grow',
delay: 200,
theme: 'tooltipster-punk'
});
}
});
JSON output from PHP:
[
{
"badges": [],
"username": "tula966",
"message": "perk added for [url=/user/?id=39691]tula966[/url]",
"avatar": "images/avatars/0f885488eb90548b5b93899615c5b838d2300bdb_thumb.jpg",
"date": "2022-02-04 01:00:01",
"last_login": "2022-02-03 12:36:06",
"user_id": "39691"
},
{
"badges": [
{
"image": "star.png",
"descr": " Star Power"
},
{
"image": "toolbox.png",
"descr": "Worker"
}
],
"username": "Tminus4",
"message": "testing testing",
"avatar": "images/avatars/8cc11eb4cb12c3d7e00abfba341c30b32ced49be_thumb.jpg",
"date": "2022-02-04 01:00:00",
"last_login": "2022-02-03 10:52:08",
"user_id": "1"
}
]
badge is not pushing the PNG file names from the JSON response to the DIV. I cant figure this out. This same code structure works perfectly on 3 other areas using the same JSON structure and logic, in fact more complex in our Site Polls area without any issues.
I also attempted to force the object with json_encode($array, JSON_FORCE_OBJECT) on the PHP side, which breaks the JS - and I have never needed to utilize that before in any case.
However this seems to differ greatly in this case. Any help is appreciated.

Showing formatted JavaScript as content in HTML

Hi I am new to JavaScript and I need to show this JavaScript object (pseudo-JSON) into a div on a HTML page, I can't use jQuery can anyone help please.
var data = {
"music": [
{
"id": 1,
"artist": "Oasis",
"album": "Definitely Maybe",
"year": "1997"
},
]
}
If you want your data to be properly formatted, JSON.stringify will natively do this for you. So in the example below, you can see we pass in the data (ignore the second argument, this is a replacer function to parse the string) and the number of formatting spaces required (in this case 2).
var data = {
"music": [{
"id": 1,
"artist": "Oasis",
"album": "Definitely Maybe",
"year": "1997"
}, ]
};
document.getElementById('target').innerHTML = '<pre><code>' + JSON.stringify(data, null, 2) + '</code></pre>';
pre {
background-color: #eee;
}
<div id="target"></div>
document.getElementById('target').innerHTML sets the html content of an element with `id="target";
The <pre> tag preserves whitespace formatting and the <code> tag tells the browser to render as is.
Not sure which data you want to show in the div. data is an object while music is a key to data. data.music will return the music array. Then use forEach array method to loop through the array.
Hope this snippet will be useful
var data = {
"music": [
{
"id": 1,
"artist": "Oasis",
"album": "Definitely Maybe",
"year": "1997"
},
]
}
var _getData = data.music // will return music array;
_getData.forEach(function(item){
document.write('<pre>'+item.id+'</pre>')
})
JSFIDDLE
You need to use dot notation. See code below
var data = {
"music": [
{
"id": 1,
"artist": "Oasis",
"album": "Definitely Maybe",
"year": "1997"
},
]
};
$('p').text(data.music[0].artist);
See jsfiddle attached
function output(inp) {
document.body.appendChild(document.createElement('pre')).innerHTML = inp; }
function syntaxHighlight(json) {
json = json.replace(/&/g, '&').replace(/</g, '<').replace(/>/g, '>');
return json.replace(/("(\\u[a-zA-Z0-9]{4}|\\[^u]|[^\\"])*"(\s*:)?|\b(true|false|null)\b|-?\d+(?:\.\d*)?(?:[eE][+\-]?\d+)?)/g, function (match) {
var cls = 'number';
if (/^"/.test(match)) {
if (/:$/.test(match)) {
cls = 'key';
} else {
cls = 'string';
}
} else if (/true|false/.test(match)) {
cls = 'boolean';
} else if (/null/.test(match)) {
cls = 'null';
}
return '<span class="' + cls + '">' + match + '</span>';
}); }
var obj = {a:1, 'b':'foo', c:[false,'false',null, 'null', {d:{e:1.3e5,f:'1.3e5'}}]}; var str = JSON.stringify(obj, undefined, 4);
output(str); output(syntaxHighlight(str));
Your JS be like
var data = {
"music": [
{
"id": 1,
"artist": "Oasis",
"album": "Definitely Maybe",
"year": "1997"
},
]
}
var item = data.music;
for(var i = 0; i<item.length; i++){
document.write(item[i].id + ", " + item[i].artist);
document.write(item[i].album);
}
JSFiddle

JSON nested Parsing Help using $.each

Below is sample JSON response. I need to parse this in a generic way instead of using transactionList.transaction[0].
"rateType": interestonly,
"relationshipId": consumer,
"sourceCode": null,
"subType": null,
"transactionList": {
"transaction": [
{
"amount": {
"currencyCode": "USD",
"value": 1968.99
},
"customData": {
"valuePair": [
{
"name": "valuePair",
"value": "001"
}
]
},
"dateTimePosted": null,
"description": "xyz",
"id": "01",
"interestAmount": {
"currencyCode": "USD",
"value": 1250
},
"merchantCategoryCode": 987654321,
"principalAmount": {
"currencyCode": "USD",
"value": 1823.8
},
"source": "Mobile Deposit",
"status": "Posted",
"type": "1"
}
]
},
I am using the following code to parse json
$.each(jsonDataArr, recursive);
function recursive(key, val) {
if (val instanceof Object) {
list += "<tr><td colspan='2'>";
list += key + "</td></tr>";
$.each(val, recursive);
} else {
if(val != null) {
if(!val.hasOwnProperty(key)) {
list += "<tr><td>" + key + "</td><td>" + val + "</td></tr>";
}
}
}
}
and this outputs as transactionList
transaction
0 and then the other keys & values. I was hoping to get transactionList and all the keys and values instead of getting the transaction and the array element. So I guess my parsing logic is not correct. Can anyone help me address this so I can just have the transactionList displayed? Thanks for your help inadvance.
It would help if we had an example of your desired results.
What if there are multiple transactions in the transactionList, how would it be displayed?
Essentially your issue is that Arrays are Objects as well.
http://jsfiddle.net/v0gcroou/
if (transactionList.transaction instanceof Object) == true
Key of transactionList.transaction is 0
Instead you need to also test if the object is an array, and do something else based on the fact you're now parsing an array instead of a string or JSON object
(Object.prototype.toString.call(val) === '[object Array]')
Another easy way would be to check the 'number' === typeof key since your JSON object does not contain numeric keys, but array objects inherently do.
http://jsfiddle.net/h66tsm9u/
Looks like you want to display a table with all your data. I added border=1 to the tables to visualize the boxes. See an example in http://output.jsbin.com/wuwoga/7/embed?js,output
function display(data) {
var html = "<table border='1'>";
var lists = recursive(data);
html += lists + "</table>";
return html;
}
function recursive(json) {
var list = "";
var instanceObj = false;
$.each(json, function(key, val){
instanceObj = (val instanceof Object);
list += [
"<tr>",
"<td>" + key + "</td>",
(instanceObj) ?
"<td><table border='1'>" + recursive(val) + "</table></td>" :
"<td>" + val + "</td>",
"</tr>"
].join("");
});
return list;
}
If you call display(json) with the json below, you'd get a display of all your data. If you add more data in the transaction array, it will display that too
var json = {
"rateType": "interestonly",
"relationshipId": "consumer",
"sourceCode": null,
"subType": null,
"transactionList": {
"transaction": [
{
"amount": {
"currencyCode": "USD",
"value": 1968.99
},
"customData": {
"valuePair": [
{
"name": "valuePair",
"value": "001"
}
]
},
"dateTimePosted": null,
"description": "xyz",
"id": "01",
"interestAmount": {
"currencyCode": "USD",
"value": 1250
},
"merchantCategoryCode": 987654321,
"principalAmount": {
"currencyCode": "USD",
"value": 1823.8
},
"source": "Mobile Deposit",
"status": "Posted",
"type": "1"
}
]
}
};

How to read array inside JSON Object this is inside another array

I am newbie to JSON, I am parsing a JSON Object and i was struck at a point where i have to read the array Elements inside a Object, that is again in another array..
Here is MY JSON
{
"DefinitionSource": "test",
"RelatedTopics": [
{
"Result": "",
"Icon": {
"URL": "https://duckduckgo.com/i/a5e4a93a.jpg"
},
"FirstURL": "xyz",
"Text": "sample."
},
{
"Result": "",
"Icon": {
"URL": "xyz"
},
"FirstURL": "xyz",
"Text": "sample."
},
{
"Topics": [
{
"Result": "",
"Icon": {
"URL": "https://duckduckgo.com/i/10d02dbf.jpg"
},
"FirstURL": "https://duckduckgo.com/Snake_Indians",
"Text": "sample"
},
{
"Result": "sample",
"Icon": {
"URL": "https://duckduckgo.com/i/1b0e4eb5.jpg"
},
"FirstURL": "www.google.com",
"Text": "xyz."
}
]
}
]
}
Here I need to read URL ,FIRSTURL and Text from RelatedTopics array and Topics array..
Can anyone help me. Thanks in advance.
Something like this
function (json) {
json.RelatedTopics.forEach(function (element) {
var url = element.Icon ? element.Icon.URL : 'no defined';
var firstURL = element.FirstURL ? element.FirstURL : 'no defined';
var text = element.Text ? element.Text : 'no defined';
alert("URL: " + url + "\nFirstURL: " + firstURL + "\nText: " + text);
if (element.Topics)
{
element.Topics.forEach(function (topicElement) {
alert("Topics - \n" + "URL: " + topicElement.Icon.URL + "\nFirstURL: " + topicElement.FirstURL + "\nText: " + topicElement.Text);
});
}
});
};
Look fiddle example
Loop through json Array like,
for(var i=0; i< RelatedTopics.length;i++){
if($.isArray(RelatedTopics[i])){
for(var j=0; j< RelatedTopics[i].Topics.length;j++){
var topics=RelatedTopics[i].Topics[j];
var text = topics.Text;
var firsturl = topics.Firsturl;
var url = topics.Icon.url;
}
}
}
if you want push it an array variable

How to parse The following JSON in Javascript?

I am making a web app for nokia S40 platform . I am calling a web service using Javascript that returns the Following JSON
{ "status_code": 200, "status_txt": "OK", "data": { "expand": [ { "short_url": "http:\/\/bit.ly\/msapps", "long_url": "http:\/\/www.microsoft.com\/web\/gallery\/?wt.mc_id=soc-in-wag-msp-M389", "user_hash": "gbL9jV", "global_hash": "eHgpGh" } ] } }
I want to obtain the "short_url" and "long_url " values
I am using eval as var obj = eval ("(" + xmlhttp.responseText + ")");
where xmlhttp.responseText conatains the JSON response.
Please help
tried this and worked
var s = '{ "status_code": 200, "status_txt": "OK", "data": { "expand": [ { "short_url": "http://bit.ly/msapps", "long_url": "http://www.microsoft.com/web/gallery/?wt.mc_id=soc-in-wag-msp-M389", "user_hash": "gbL9jV", "global_hash": "eHgpGh" } ] } } '
var d = JSON.parse(s);
console.log(d.data.expand[0].short_url);
console.log(d.data.expand[0].long_url);
This expression
JSON.parse('{ "status_code": 200, "status_txt": "OK", "data": { "expand": [ { "short_url": "http:\/\/bit.ly\/msapps", "long_url": "http:\/\/www.microsoft.com\/web\/gallery\/?wt.mc_id=soc-in-wag-msp-M389", "user_hash": "gbL9jV", "global_hash": "eHgpGh" } ] } }').data.expand[0].short_url
returns "http://bit.ly/msapps"
How about this
var json = "{}" // Your JSON string
json = new Function('return ' + json)();
console.log(json.data.expand[0].short_url, json.data.expand[0].long_url);

Categories

Resources