I am fairly new to Javascript and nodejs. I would like a JSON file (results.json) that takes the format of something similar to this:
Starts off as:
{
"name":"John",
"task":[]
}
then eventually becomes something like this with nested arrays:
{
"name":"John",
"task":[ ["task1","task2"], ["task3", "task4"] ]
}
I want to push to the "task" array a new list of tasks (always of size 2) everytime something is done (in my case when a form is submitted with a button-press).
So for example, after another "action", the JSON file will look something like this:
{
"name":"John",
"task":[ ["task1","task2"], ["task3", "task4"] , ["task5", "task6"] ]
}
NOTE: "task(1,2,...,6) was just used as an example, these will be other strings corresponding to the form submission.
This is what I have so far in my server-side file:
var fs = require('fs')
app.post("/addtask", function(req, res) {
fs.readFile('results.json', function (err, data) {
var json = JSON.parse(data)
var newTask1 = req.body.newtask1
var newTask2 = req.body.newtask2
//WHAT DO I PUT HERE
fs.writeFile("results.json", JSON.stringify(json))
})
});
Please do correct me if my syntax is wrong or if my idea of how a JSON file works is wrong.
Just push the data as an array
var resObj= {
"name":"John",
"task":[]
}
var newTask1 = "task1";
var newTask2 = "task2";
resObj.task.push([newTask1,newTask2]);
console.log(resObj);
Related
I have a python list called "devices" that looks something like this:
[{
'Version': 'V14E',
'DeviceID': 'e00fce68281671574f416a8c',
'TerminationDate': '2050-12-31',
'Latitude': 31.322139613573903,
'ActivationDate': '2021-01-04',
'Longitude': -101.93960164357534,
'DeviceName': 'Hans_Gruber-1'
}, {
'Version': 'V14E',
'DeviceID': 'e00fce68e1265e12e12fa02a',
'TerminationDate': '2050-12-31',
'Latitude': 31.32151602493975,
'ActivationDate': '2021-01-04',
'Longitude': -101.93948944894449,
'DeviceName': 'Hans_Gruber-2'
}]
In my flask app, I pass this list to my html file by the name "devices_test" using json.dumps() to correctly format the data to be used in java script.
return render_template("json_form.html",
devices = devices, components = components, operator = operator, name = site_name,
devices_test = json.dumps(devices))
Here is me trying to test out an answer I have seen on another post here via the "data" variable:
function update_device_form(strDevice) {
var data = {
{
devices_test | safe
}
};
var device_index = document.getElementById("devices").selectedIndex;
if (device_index == 0) { //IOW if no device is selected
document.getElementById("device_id").value = "";
} else {
document.getElementById("device_id").value = '';
}
But I get errors such as "Declaration or statement expected" and "Property assignment expected" and "',' expected". What am I doing wrong here?
You can use string to remove the error var data = "{{devices_test|safe}}"
Now data is not javascript object, it is a string, you need to use JSON.parse and also replaceAll.
var data = "{{devices_test|safe}}"
var data = data.replaceAll("'",'"') // replace single quote to double
var data = JSON.parse(data)
one line
var data = JSON.parse("{{devices_test|safe}}".replaceAll("'",'"'))
Imagine if I want to wait to get JSON file If they post to me. I can get it. if it's not I waite for it. I want to get it and store it and parse it to work on it.
(I need to receive the request )How I can have JSON file I can get it to take what I need then post my HTTP response to the agent that sends me file that file.
my JSON file name is : flow_demo_1
var device_array = { device_id : [["7547092d-e03e-5148-a54f-8276a85d7f70","cpp_node_192-168-56-1:6111"]] };
var from_file_array = [
{ device_id_from_file: "7547092d-e03e-5148-a54f-8276a85d7f70" },
{ device_id_from_file: "93e71ba7-fb56-5592-a5f6-d855203dd7ae" },
{ device_id_from_file: "93e71ba7-fb56-5592-a5f6-d855203dd7ae" },
{ device_id_from_file: "fe21abdf-706f-5c7b-adb8-2507e145e820" },
];
var val = device_array['device_id'][0][0];
for (var i= 0; i < from_file_array.length; i++) {
if(from_file_array[i].device_id_from_file === val){
console.log("device ids are matches");
};
};
try this,you just want the which file data is matched right?
from_file_array.filter(each=>each.device_id_from_file===device_array.device_id[0][0])
it will give the matched device_id_from_file;if not you will get empty array
I am trying to find a way to use data from my .json file in the pre-request script in Postman.
As you can see in the code below I am using a loop for my request.
In my pre-request script i would like to use "id_group":"14803,14805" from my file Data.json instead of id_group = ["14803","14805"];.
Thanks
URL:
.../group/{{id_of_group}}/members
Body:
{
"id_user": {{id_user}}
}
Pre-request script:
var id_group = pm.environment.get("id_group");
if (!id_group) {
id_group = ["14803","14805"];
}
var currentIdGroup = id_group.shift();
pm.environment.set("id_of_group", currentIdGroup);
pm.environment.set("id_group", id_group);
Tests:
var id_group = pm.environment.get("id_group");
console.log(id_group);
if (id_group && id_group.length > 0) {
postman.setNextRequest('Add user to groups');
} else {
postman.setNextRequest();
}
Data.json file:
[{
"id_user":47091,
"id_group":"14803,14805"
}]
You are creating an Array-Object. But the pm.environment.set() stores only strings.
You must convert them into strings with JSON.stringify().
Instead of pm.environment.set("id_of_group", currentIdGroup); i would suggest
pm.environment.set("id_of_group", JSON.stringify(currentIdGroup));
And backwards the same. If you are loading from the env vars, you have to parse your stringified objects:
JSON.parse(pm.environment.get("id_group"));
I have just found an answer.
In the pre-request script I use the variable id_group, this variable is used to get the id's which are going to be used in the loop.
I found pm.iterationData.get();, it will take the data from the JSON file. Instead of id_group = ["14803","14805"]; I use pm.iterationData("id_group").
My pre request script look like this now:
var id_group = pm.environment.get("id_group");
if (!id_group) {
id_group = pm.iterationData.get("id_group");
}
var currentIdGroup = id_group.shift();
pm.environment.set("id_of_group", currentIdGroup);
pm.environment.set("id_group", id_group);
And I cheat a little, my JSON look like this now:
[{
"id_user":47091,
"id_group":["14803","14805"]
}]
I have a JSON file which contains:
[{"id":1,"first_name":"Judith","email":"jshaw0#wikipedia.org"},
{"id":2,"first_name":"Sarah","email":"sross1#infoseek.co.jp"},
{"id":3,"first_name":"Dorothy","email":"dgreene2#posterous.com"},
{"id":4,"first_name":"Christine","email":"cnichols3#techcrunch.com"},
{"id":5,"first_name":"Theresa","email":"trogers4#xrea.com"},
{"id":6,"first_name":"Rebecca","email":"rpeterson5#mlb.com"},
{"id":7,"first_name":"Chris","email":"cbailey6#yellowpages.com"},
{"id":8,"first_name":"Howard","email":"hbailey7#miibeian.gov.cn"},
{"id":9,"first_name":"Sara","email":"ssimpson8#techcrunch.com"},
{"id":10,"first_name":"Lois","email":"lmartinez9#dion.ne.jp"},
{"id":11,"first_name":"Jeffrey","email":"jhalla#intel.com"},
{"id":12,"first_name":"Teresa","email":"tcampbellb#usnews.com"},
{"id":13,"first_name":"Susan","email":"skingc#wired.com"},
{"id":14,"first_name":"Richard","email":"rpattersond#omniture.com"},
{"id":15,"first_name":"Ronald","email":"rgreenee#wordpress.org"}]
I want to add one more element to it but I can't figure it out how.
I have the following node code:
var jsonfile = require('jsonfile');
var util = require('util');
var file = 'data.json';
var jsonObj = {};
jsonfile.readFile(file, function(err, obj) {
jsonObj = obj;
new_obj = {"id":16,"first_name":"Florin","email":"popflorin1705#yahoo.com"};
//jsonObj.push(new_obj)
console.log(typeof jsonObj);
/*jsonfile.writeFile(file, jsonObj, function (err) {
console.error(err)
})*/
});
I've tried to use push method, but obviously is not working because it is an object not an array, even if it looks as an array. Which would be a good way to add another row at the end of the object (or array - I'm confused)?
I believe you're forgetting to parse JSON. After reading the file, your code should be:
jsonObj = JSON.parse(obj);
instead of straight assignment.
Declare the variable
var new_obj = {"id":16,"first_name":"Florin","email":"popflorin1705#yahoo.com"};
And then use push() as you have done already. Give it a try. It will work only if obj is json object as you mentioned in question.
I am new to JavaScript and I'm trying to read data from a file and save it in list so that I can retrieve it later. Something like:
sample.json
{
"circles": [
{"x":14,"y":2,"z":4,"r":50},
{"x":14,"y":2,"z":4,"r":50}
]
}
What I am looking for is:
var circle_list = []
circle_lst = some_function_which_reads_json_from_file('sample.json')
//Now circle list contains
circle_list = [
{"x":14,"y":2,"z":4,"r":50},
{"x":14,"y":2,"z":4,"r":50}
]
Later I can just do something like:
for (var i = 0; i <circle_list.lenght;i++){
//do osmething
}
I was looking into
$.getJSON("sample.json" , function(data){
//
});
But then I came to know this call is asynchronous... But I need to maintain execution order.
Don't maintain execution order. This will lock up the browser during the fetching. Use this only as an absolute last resort:
var circle_list;
$.ajax({'dataType': 'json', url: 'sample.json', 'async': false})
.done(function(json) {
circle_list = json;
});
Instead, you can do at least a couple of other things:
Work with callback. It doesn't have to all be in one spot thanks to deferreds.
Load the JSON along with the rest of the page and fetch it from the DOM.