So I have an existing JSON file where the login data is stored. How can I add new users to this JSON file with JavaScript or JQuery?
This is my JSON-File:
{
"users": [
{
"username": "Tim",
"password": "test1"
},
{
"username": "Tom",
"password": "test2"
}
]
}
At the first put your data from login in data
var data = {
"users": [
{
"username": "Tim",
"password": "test1"
},
{
"username": "Tom",
"password": "test2"
}
]
}
And after that you shoud parse your json and put in jsonData and push your new user in it.
var jsonData = JSON.parse(data); //parse the JSON
jsonData.users .push({ //add new user
username :"Mohammad",
password :"test3",
});
At the end stringfy your json data to a string
data= JSON.stringify(jsonData);
Related
This feels like a really stupid question, but my lack of JS knowledge combined with lack of AWS knowledge has me in a tight spot! I'm just trying to get to grips with a basic AWS stack i.e. Lambda/Dynamo/API Gateway for some basic API work.
If I want a simple API endpoint to handle PUT requests e.g. https://my.endpoint.amazonaws.com/users. If I have a DynamoDB table with a composite primary key of userID and timestamp I could use the code snippet below to take the unknown data (attributes that weren't known when setting a schema), but this obviously doesn't work well
const dynamo = new AWS.DynamoDB.DocumentClient();
let requestJSON = JSON.parse(event.body);
await dynamo
.put({
TableName: "myDynamoTable",
Item: {
userID: requestJSON.userID,
timestamp: requestJSON.timestamp,
data: requestJSON.data
}
})
.promise();
I could send a PUT request with the following JSON
{
"userID": "aaaa1111",
"timestamp": 1649677057,
"data": {
"address": "Elm Street",
"name": "Glen"
}
}
but then address and name get shoved into a single DynamoDB attribute named data. How do I construct the node code to create a new attribute named address and one named name with the corresponding values, if I didn't know these attributes i.e. I want to use JSON in my request like below, but assuming I don't know this and can't use requestJSON.address
{
"userID": "aaaa1111",
"timestamp": 1649677057,
"address": "Elm Street",
"name": "Glen"
}
You can use the spread operator, for example:
const data = {
address: "Elm Street",
name: "Glen",
};
const item = {
userID: "aaaa1111",
timestamp: 1649677057,
...data,
};
console.log("item:", item);
If you insist on the API contract as
{
"userID": "aaaa1111",
"timestamp": 1649677057,
"data": {
"address": "Elm Street",
"name": "Glen"
}
}
then you can do mapping on the TypeScript level
const request: {userID: string, timestamp: number, data: any} = {
"userID": "aaaa1111",
"timestamp": 1649677057,
"data": {
"address": "Elm Street",
"name": "Glen"
}
};
const ddbObject: any = {
"userID": request.userID,
"timestamp": request.timestamp
};
Object
.keys(request.data)
.forEach(key => ddbObject[key] = request.data[key]);
Representation of ddbObject is
{
"userID": "aaaa1111",
"timestamp": 1649677057,
"address": "Elm Street",
"name": "Glen"
}
I have a json file like below:
{
"users": [
{
"id": "person1",
"information": [
{
"first_name": "Mike",
"last_name": "Patty",
"address": ["address1","address2"]
},
{
"first_name": "Mike2",
"last_name": "Patty2",
"address": ["address1","address2"]
}
]
},
{
"id": "person2",
"information": [
{
"first_name": "Tom",
"last_name": "Jerry",
"address": ["address1","address2"]
},
{
"first_name": "Tom2",
"last_name": "Jerry2",
"address": ["address1","address2"]
}
]
}
]
}
I would like to iterate users and add each user's information to the API database. addInfo request requires: first_name, last_name and address (address is array). It is because I need to save response from information request for later use. I am pretty new to angular/typescript. So here is what I am trying to code so far:
Thank you in advance!
forkjoin need an array of observables, execute the observables, and, when all the onbservables are completed return the response of each one. So you should create this array of observables. For this, you convert your array "users" in an array of call API. For this you use "map" (is the "map of an array")
const addUsers$ = forkJoin(
User.map(x=>
//each "x" is in the way {id:..,information:{first_name:..,last_name:..,address:..}
this.APIservice.addInformation(
{
firstName: x.information.first_name,
lastName: x.information.last_name,
organizations: x.information.address
}
)).subscribe((res:any[])=>{
//in res[0] you has the response to the first call API,
//in res[1] you has the response to the second one
//...
})
Try flatMap
const addUsers$ = forkJoin(
Users.flatMap(user => user.information).map(info =>
this.APIservice.addInformation(
{
firstName: info.first_name,
lastName: info.last_name,
organizations: info.address
}
)))
);
How can i modify the value of a field searching the object by another field?
the object looks like this:
{
"_id": {
"$oid": "607b8b1fdd12a63f0499c207"
},
"username": "paul",
"password": "123456",
"question": "q2",
"answer": "cucu"
}
and i wanna modify the password, searching the object by the username,
i tried this but does not work:
var dbc = db.db("chat");
dbc.collection("accounts").update({username: { $eq: user}},{$set: { password : newpass}});
This worked for me ({$eq: "paul"} is the same of "paul" in this case)
db.getCollection('accounts').update({username:"paul"},{$set: { password : "newpass"}})
I'm using Node.js to:
Query an external API.
Save JSON result to file.
Import query result to MongoDB.
Example of code:
//Query the API and save file
var file = '../data/employees.json';
tl.employees.all(function(response) {
fs.writeFile(file, JSON.stringify(response, function(key, value) {
var result = value;
return result;
}, 3, 'utf8'));
//Inserts API response above to MongoDB
var insertDocument = function(db, callback) {
db.collection('employees').insert(response, function(err, result) {
assert.equal(err, null);
console.log("Step 2: Inserted Employees");
callback();
});
};
This is all working fine, and I'm getting the following JSON saving to file and importing to MongoDB:
{
"data": [
{
"full name": "Keith Richards",
"age": 21,
"userName": "keith1#keith.com",
"employeeDetails": {
"id": 102522
}
},
{
"full name": "Jim Morrison",
"age": 27,
"userName": "jim#jim.com",
"employeeDetails": {
"id": 135522
}
}
]
}
The problem is that this gets imported to MongoDB as 1 object because of the "data" part.
Like this:
{
"_id" : ObjectId("58ae5ceac10d7a5005fc8370"),
"data" : [
{ // contents as shown in JSON above ..
This makes aggregation and matching really hard (or not possible).
Is there a way of stripping out the "data" part and only importing the contents of it, so each 'employee' would become it's own object like this:
[
{
"_id" : ObjectId("58ae5ceac10d7a5005fc8370"),
"full name": "Keith Richards",
"age": 21,
"userName": "keith1#keith.com",
"employeeDetails": {
"id": 102522
}
},
{
"_id" : ObjectId("234332c10d7a5005fc8370"),
"full name": "Jim Morrison",
"age": 27,
"userName": "jim#jim.com",
"employeeDetails": {
"id": 135522
}
}
]
So you can parse the Json before sending it to file. After getting the result, use parseJSON(data) to check if it contains "data" field. if yes, get the arrays inside that and store them to file.
Basically, I have explained a bit more to what #Bertrand has said.
Hope this helps.
Hi all I am creating a Json and adding it to Sessionstorage as follows
<script type="text/javascript">
function addMoreProducts() {
if (sessionStorage.getItem("empData") === null) {
var empInformation = {
"employees": [
{ "firstName": "John", "lastName": "Doe" },
{ "firstName": "Anna", "lastName": "Smith" },
{ "firstName": "Peter", "lastName": "Jones" }
]
}
var x = JSON.stringify(empInformation);
sessionStorage.setItem("empData", x);
}
else {
if (sessionStorage.getItem("empData") != null) {
var empInformation = {
"employees": [
{ "firstName": "John1", "lastName": "Doe1" },
{ "firstName": "Anna1", "lastName": "Smith1" },
{ "firstName": "Peter1", "lastName": "Jones1" }
]
}
var v = sessionStorage.getItem("empData").toString();
var jParse = JSON.stringify(v);
var jparse1 = JSON.stringify(empInformation);
var arrayOfObjects = [jParse, jparse1];
}
var vparse = JSON.stringify(arrayOfObjects);
var vparse1 = JSON.parse(vparse);
sessionStorage.removeItem('empData');
sessionStorage.setItem("empData", vparse);
}
}
</script>
But when I retrieve the data from sessionStorage after assigning data this is not giving me proper json format can some one help me. This is the format I am getting
"["\"{\\"employees\\":[{\\"firstName\\":\\"John\\",\\"lastName\\":\\"Doe\\"},{\\"firstName\\":\\"Anna\\",\\"lastName\\":\\"Smith\\"},{\\"firstName\\":\\"Peter\\",\\"lastName\\":\\"Jones\\"}]}\"","{\"employees\":[{\"firstName\":\"John1\",\"lastName\":\"Doe1\"},{\"firstName\":\"Anna1\",\"lastName\":\"Smith1\"},{\"firstName\":\"Peter1\",\"lastName\":\"Jones1\"}]}"]"
When I watch it in console. Also I am using restful service where my service holds a datatable as a parameter how can I pass this json object to that method as DataTable
This is actually a very wide discussed issue:
This is what is proposed by microsof in this article
If this function causes a JavaScript parser error (such as "SCRIPT1014: Invalid character"), the input text does not comply with JSON syntax. To correct the error, do one of the following:
Modify the text argument to comply with JSON syntax. For more information, see the BNF syntax notation of JSON objects.
For example, if the response is in JSONP format instead of pure JSON, try this code on the response object:
var fixedResponse = response.responseText.replace(/\\'/g, "'");
var jsonObj = JSON.parse(fixedResponse);