how to write json files in javascript - javascript

Ok, so I am programming a web operating system using js. I am using JSON for the file system. I have looking online for tutorials on JSON stuff for about a week now, but I cannot find anything on writing JSON files from a web page. I need to create new objects in the file, not change existing ones. Here is my code so far:
{"/": {
"Users/": {
"Guest/": {
"bla.txt": {
"content":
"This is a test text file"
}
},
"Admin/": {
"html.html": {
"content":
"yo"
}
}
},
"bin/": {
"ls": {
"man": "Lists the contents of a directory a files<br/>Usage: ls"
},
"cd": {
"man": "Changes your directory<br/>Usage: cd <directory>"
},
"fun": {
"man": "outputs a word an amount of times<br/>Usage: fun <word> <times>"
},
"help": {
"man": "shows a list of commands<br/>Usage: help"
},
"clear": {
"man": "Clears the terminal<br/>Usage: clear"
},
"cat": {
"man": "prints content of a file<br/>Usage: cat <filename>"
}
},
"usr/": {
"bin/": {
},
"dev/": {
}
}
}}

I think the better solution is to stringify your JSON, encode with base64 encoding and then send it to a server-side script (a PHP page, for instance) which could save this file. See:
var json = JSON.stringify(myJson);
var encoded = btoa(json);
You can use ajax for sending:
var xhr = new XMLHttpRequest();
xhr.open('POST','myServerPage.php',true);
xhr.setRequestHeader('Content-type','application/x-www-form-urlencoded');
xhr.send('json=' + encoded);
And in the server-side:
$decoded = base64_decode($_POST['json'])
$jsonFile = fopen('myJson.json','w+');
fwrite($jsonFile,$decoded);
fclose($jsonFile);

I'd take off the "/"'s from the keys then could split on "/" and walk the tree by shifting values off the result. For example, the following code will create the full path if it doesn't already exist, but preserving the folder & contents if it does.
var fs = {
"bin": {
"mkdir": function(inPath) {
// Gets rid of the initial empty string due to starting /
var path = inPath.split("/").slice(1);
var curFolder = fs;
while(path.length) {
curFolder[path[0]] = curFolder[path[0]] || {};
curFolder = curFolder[path.shift()];
}
}
}
}
fs.bin.mkdir("/foo/bar");
console.log(JSON.stringify(fs, function(key,val) {
if(key === 'mkdir') return undefined;
return val;
}, 2));
Output:
{
"bin": {},
"foo": {
"bar": {}
}
}
As others have mentioned, rather than building the JSON object by hand with strings, to avoid syntax errors (and frustration), building it through code then using JSON.stringify to get the final result would likely be simpler.

Related

How to access a specific element in JSON in Google Apps Script?

I need to access the nav for a specific date from the below JSON. eg : data[date="20-04-2022"].nav
How do I do it in Google Apps Script?
The standard JSON notation is not working.
{
"meta":{
"fund_house":"Mutual Fund",
"scheme_type":"Open Ended Schemes",
},
"data":[
{
"date":"22-04-2022",
"nav":"21.64000"
},
{
"date":"21-04-2022",
"nav":"21.69000"
},
{
"date":"20-04-2022",
"nav":"21.53000"
}
],
"status":"SUCCESS"
}
In your situation, I thought that it is required to retrieve the element including "date": "20-04-2022" from the array of data. So, how about the following sample script?
Sample script:
const obj = {
"meta": {
"fund_house": "Mutual Fund",
"scheme_type": "Open Ended Schemes",
},
"data": [
{
"date": "22-04-2022",
"nav": "21.64000"
},
{
"date": "21-04-2022",
"nav": "21.69000"
},
{
"date": "20-04-2022",
"nav": "21.53000"
}
],
"status": "SUCCESS"
};
const search = "20-04-2022";
const res = obj.data.find(({ date }) => date == search);
const value = res && res.nav;
console.log(value) // 21.53000
For example, if the search value is always found, you can use the following script.
const res2 = obj.data.find(({ date }) => date == search).nav;
Reference:
find()
Added 1:
From your following reply,
This looks like standard java script. Does not work in google apps script(script.google.com/home). Getting syntax error for this line : const res = obj.data.find(({ date }) => date == search);
I'm worried that you are not enabling V8 runtime. Ref If you cannot use V8 runtime, how about the following sample script?
Sample script:
var obj = {
"meta": {
"fund_house": "Mutual Fund",
"scheme_type": "Open Ended Schemes",
},
"data": [
{
"date": "22-04-2022",
"nav": "21.64000"
},
{
"date": "21-04-2022",
"nav": "21.69000"
},
{
"date": "20-04-2022",
"nav": "21.53000"
}
],
"status": "SUCCESS"
};
var search = "20-04-2022";
var res = obj.data.filter(function (e) { return e.date == search })[0];
var value = res && res.nav;
console.log(value) // 21.53000
Added 2:
From your following reply,
This looks like standard java script. Does not work in google apps script(script.google.com/home). Getting syntax error for this line : const res = obj.data.find(({ date }) => date == search);
I am trying to write a google apps script to fetch data from a url. But google seems to have its own way of handling the JSON data which I am unable to figure out. developers.google.com/apps-script/guides/services/…
I understood that your actual goal was to retrieve the value using Web Apps. If my understanding of your actual goal, how about the following sample script?
1. Sample script:
Please copy and paste the following script to the script editor and save the script.
function doGet(e) {
var search = e.parameter.search;
var obj = {
"meta": {
"fund_house": "Mutual Fund",
"scheme_type": "Open Ended Schemes",
},
"data": [
{
"date": "22-04-2022",
"nav": "21.64000"
},
{
"date": "21-04-2022",
"nav": "21.69000"
},
{
"date": "20-04-2022",
"nav": "21.53000"
}
],
"status": "SUCCESS"
};
var res = obj.data.filter(function (e) { return e.date == search })[0];
var value = res && res.nav;
return ContentService.createTextOutput(value);
}
I think that this sample script can be used with and without V8 runtime.
2. Deploy Web Apps.
In this case, please check the official document. Please set it as follows.
Execute as: Me
Anyone with Google account: Anyone
In this case, it supposes that you are using new IDE. Please be careful this.
3. Testing.
Please access to the URL like https://script.google.com/macros/s/{deploymentId}/exec?search=20-04-2022 using your browser. By this, the result value is returned.
`

Matching query images with JSON variable in Gatsby

So, I have a JSON file that has info I'm pulling into my React project. One of those fields is an image keyword. I want to use that to call images in a "show" folder where promo images can be dumped.
thisYear.json
{
"title": "Rope",
"author": "Patrick Hamilton",
"image": "rope",
},{
"title": "I Hate Hamlet",
"author": "Paul Rudnick",
"image": "iHateHamlet",
}
]
I made a query that is grabbing the images from said "show" folder to the jsx file
{
allFile(filter: {relativeDirectory: {eq: "shows"}}) {
edges {
node {
id
name
childImageSharp {
gatsbyImageData(placeholder: DOMINANT_COLOR)
}
}
}
}
}
I've tried to write some functions that compare the name properties, but I just can't seem to write anything that works. I'm not grasping something here and I just don't know what it is.
The showImage is passed in while I'm mapping through my JSON file and comparing with imageData, which is the query data. The console log is showing the right names being compared, so I know it's passing through. it's just not passing that data to the GatsbyImage.
function findImage(showImage) {
imageData.map((image) => {
console.log(image.node.name + ' vs ' + showImage)
if (image.node.name == showImage) {
/**if the image name == our show image name, we return that image data */
return data.file.childImageSharp.gatsbyImageData
}
})
return
}
My git repository is here if it helps:
https://github.com/TheComeBackGuy/TKD-Gatsby
Well, I figured out what I was doing wrong. I wasn't returning the answer to the root of the function. I'm sure a more experienced person could write it cleaner, but here's what I used.
export default function FindImage(queryArray, showImage) {
let returnStatement = null
queryArray.map((images) => {
if (images.node.name == showImage) {
console.log(showImage + ' vs ' + images.node.name)
console.log(images.node.childImageSharp.gatsbyImageData)
returnStatement = images.node.childImageSharp.gatsbyImageData
}
})
return returnStatement
}

What is wrong with my JSON output for a Slack Message payload?

I have set up what I think should be a working JSON output to send a message in slack but Slack keeps rejecting it.
I have tried multiple different message layout formats using the guides on slack's api site, but so far the only method that has successfully sent is a fully flat JSON with no block formatting.
function submitValuesToSlack(e) {
var name = e.values[1];
var caseNumber = e.values[2];
var problemDescription = e.values[3];
var question = e.values[4];
var completedChecklist = e.values[5];
var payload = [{
"channel": postChannel,
"username": postUser,
"icon_emoji": postIcon,
"link_names": 1,
"blocks": [
{
"type": "section",
"fields": [
{
"type": "mrkdwn",
"text": "*Name:*\n " + name
}
]
}]
}];
console.log(JSON.stringify(payload, null, "\t"));
var options = {
'method': 'post',
'payload': JSON.stringify(payload)
};
console.log(options)
var response = UrlFetchApp.fetch(slackIncomingWebhookUrl, options);
}
When I run this, I get the following output:
[
{
"channel":"#tech-support",
"username":"Form Response",
"icon_emoji":":mailbox_with_mail:",
"link_names":1,
"blocks":[
{
"type":"section",
"fields":[
{
"type":"mrkdwn",
"text":"*Name:*\n test"
}
]
}
]
}
]
Which I believe is correct, however slack api just rejects it with an HTTP 400 error "no text"
am I misunderstanding something about block formatting?
EDIT:
To Clarify, formatting works if I use this for my JSON instead of the more complex format:
{
"channel":"#tech-support",
"username":"Form Response",
"icon_emoji":":mailbox_with_mail:",
"link_names":1,
"text":"*Name:*\n test"
}
The reason you are getting the error no_text is because you do not have a valid message text property in your payload. You either need to have a text property as top line parameter (classic style - your example at the bottom) or a text block within a section block.
If you want to put to use blocks only (as you are asking) the section block is called text, not fields. fields is another type of section bock that has a different meaning.
So the correct syntax is:
[
{
"channel":"#tech-support",
"username":"Form Response",
"icon_emoji":":mailbox_with_mail:",
"link_names":1,
"blocks":[
{
"type":"section",
"text":[
{
"type":"mrkdwn",
"text":"*Name:*\n test"
}
]
}
]
}
]
Also see here for the official documentation on it.
Blocks are very powerful, but can be complicated at times. I would recommend to use the message builder to try out your messages and check out the examples in the docu.

Replacing JSON strings with images

I have a table column that's populated by documents and in the next column I've rendered what the file extension of that document is (i.e. .docx).
I want to be able to replace the file extension text with icon images that are locally stored (folder/src/SiteAssets/Images/docx.gif).
Would I be able to work with the original code I have:
// -- Generating extension names -- //
function docType(fileName) {
return [fileName].filter(function() {
return true;
}).map(function(fileName) {
return fileName.split('.').pop();
}).pop();
}
to replace the text with the icons? I was thinking of something like if (extension===true), replace with icon.gif. If need be I can get rid of this code and work with something else.
Loading document data:
$.noConflict();
let tableRes = JSONfile.d.results.filter(function(val) {
return (val.FileLeafRef.trim().length > 0);
}).map(function(obj) {
return {
"Path": obj.EncodedAbsUrl,
"Titles": obj.File.Name,
"Categories": obj.ResourceType.results.map(function(val) {
return val.Label;
}).join(";"),
"Blank": "",
"docImg": docType(obj.File.Name) // "Getting the docType of obj.File.Name"
}
})
Rendering table:
$('#km-table-id').DataTable( {
columns: [
// { data: "Blank" },
{ data: "Categories" }, // hidden
{ data: "docImg" },
{ data: "Titles" }
],
...etc

How do I import JSON file data into JS file and output the JSON data in JS console?

I have a list of data in my JSON file. I am trying to output certain strings and arrays from my JSON file via my JS. How do I go on about this? All these files are saved on my desktop.
I've tried Xhttp code. But I think I need some server going on for that, and I don't have that. Also, I'm pretty sure this should be possible without having to use a server?
PS: the json file is named: movie.json
JSON CODE
{
"movie": {
"name": "drive",
"year": "2011",
"people": {
"actors": [
{
"name": "ryan gosling"
},
{
"name": "cary mulligan"
},
{
"name": "bryan cranston"
}
]
}
}
}
JS CODE
function preload() {
var movie = load.JSON("movie.json");
}
function(movie) {
var movie = JSON.parse(movie);
console.log(movie[0].name);
console.log(movie[0].year);
console.log(movie[0].actors);
}();
drive, 2011, ryan gosling, cary mulligan, bryan cranston
var movie;
var http = new XMLHttpRequest();
xhhtp.open( "GET", "movie.json", true);
xhttp.onreadystatechange = function () {
if(http.readyState == 4 && http.status == 200) {
movie = JSON.parse(http.responseText);
}
}
http.send();
console.log(movie[0].name);
console.log(movie[0].year);
console.log(movie[0].actors);
I do not know if the code above will help you. Using XMLHttpRequest will help you fetch the json file then you can parse and sort into array. Note: you do not need a server to use XMLHttpRequest, if you have text editor like VSCode you can us it to run live HTML codes then you can get the full link to the JSON file you want to parse e.g localhost:9000/movie.json

Categories

Resources