I have sent a post request to node express server
app.post('/addUsers', function (req, res) {
var newuser = req.body;
console.log(newuser);
fs.readFile( __dirname + "/" + "users.json", 'utf8', function (err, data) {
data = JSON.parse( data );
data["user4"] = newuser // how can i create a user4 here currently i get an error as newsier is whole req body or something .
console.log( data );
// res.end(data);
res.end( JSON.stringify(data));
});
})
and i have got the value of newuser to console as
{ '{"user4":{"password":"killer","id":4,"profession":"kuchbhi","name":"mukesh"}}': '' }
The question is how can i get the value of user4 so that i can add it to the list of users .
I was using this dictionary in swift
["user4":["name" : "mukesh",
"password" : "killer",
"profession" : "kuchbhi",
"id": 4]]
which i changed to this once knowing its not valid json
["name" : "mukesh",
"password" : "killer",
"profession" : "kuchbhi",
"id": 4]
and know i don't get the error but the data from server response (i have printed it in Xcode console)after adding the fourth user is quite not in the format i think it should be , it looks like this
["user2": {
id = 2;
name = suresh;
password = password2;
profession = librarian;
}, "user4": {
"{\"password\":\"killer\",\"profession\":\"kuchbhi\",\"id\":4,\"name\":\"mukesh\"}" = "";
}, "user1": {
id = 1;
name = mahesh;
password = password1;
profession = teacher;
}, "user3": {
id = 3;
name = ramesh;
password = password3;
profession = clerk;
}]
all other entries are added by me manually in users.son.
This is what is logged into terminal console
user4: { '{"password":"killer","profession":"kuchbhi","id":4,"name":"mukesh"}': '' } }
which i still think is not good json or is it ?
Thank you quite a novice with format conversions and servers get/post thingy .
At the moment, the json that you receive/present is not valid.
Once you actually manage to receive valid JSON from the client, this will look like the following.
var u = {"user4":{"password":"killer","id":4,"profession":"kuchbhi","name":"mukesh"}};
For any json you can get its keys by using the command
var theKeys = Object.keys(u);
In the example above, there is only one key for the entire JSON, so the variable theKeys has contents [ 'user4' ]. Hence, you will be able to access the username that you want by looking at theKeys[0].
Similarly, you can get the properties for the inner json document using the command
Object.keys(u[theKeys[0]]);
which will return [ 'password', 'id', 'profession', 'name' ].
EDIT
Based on the comment below, perhaps the following code can help you send the json object correctly from the client side.
NSDictionary *aDictionary = #{
#"user4": #{#"password": #"killer",
#"id": #4,
#"profession": #"kuchbhi"
}};
NSError * error;
NSData * theData = [NSJSONSerialization dataWithJSONObject:aDictionary options:0 error:&error];
NSString * newStr = [[NSString alloc] initWithData:theData encoding:NSUTF8StringEncoding];
NSLog(#"body: %#", newStr);
[newStr release];
And here is a solution to send json correctly using swift: https://stackoverflow.com/a/31938246/1355058
Related
I have this JSON file.
Using rescript I want to :
Read the file.
Extract data from the file.
Write result in a new file.
{
"name": "name",
"examples": [
{
"input": [1,2],
"result": 1
},
{
"input": [3,4],
"result": 3
}
],
}
I was able to acheive this using JavaScript
var file = Fs.readFileSync("file.json", "utf8");
var data = JSON.parse(file);
var name = data.name
var examples = data.examples
for (let i = 0; i< examples.length; i++){
let example = examples[i]
let input = example.input
let result = example.result
let finalResult = `example ${name}, ${input[0]}, ${input[1]}, ${result} \n`
Fs.appendFileSync('result.txt',finalResult)
}
These are my attempts at writing it in Rescript and the issues I ran into.
let file = Node.Fs.readFileSync("file.json", #utf8)
let data = Js.Json.parseExn(file)
let name = data.name //this doesn't work. The record field name can't be found
So I have tried a different approach (which is a little bit limited because I am specifying the type of the data that I want to extract).
#module("fs")
external readFileSync: (
~name: string,
[#utf8],
) => string = "readFileSync"
type data = {name: string, examples: array<Js_dict.t<t>>}
#scope("JSON") #val
external parseIntoMyData: string => data = "parse"
let file = readFileSync(~name="file.json", #utf8)
let parsedData = parseIntoMyData(file)
let name = parsedData.name
let example = parsedData.examples[0]
let input = parsedData.examples[0].input //this wouldn't work
Also tried to use Node.Fs.appendFileSync(...) and I get The value appendFileSync can't be found in Node.Fs
Is there another way to accomplish this?
It's not clear to me why you're using Js.Dict.t<t> for your examples, and what the t in that type refers to. You certainly could use a Js.Dict.t here, and that might make sense if the shape of the data isn't static, but then you'd have to access the data using Js.Dict.get. Seems you want to use record field access instead, and if the data structure is static you can do so if you just define the types properly. From the example you give, it looks like these type definitions should accomplish what you want:
type example {
input: (int, int), // or array<int> if it's not always two elements
result: int,
}
type data = {
name: string,
examples: array<example>,
}
I'm new to LUA and tried learning coding this language with Garrys Mod.
I want to get the messages from the Garrys Mod chat and send them into a Discord channel with a webhook.
It works, but I tried expanding this project with embeded messages. I need JSON for this and used json.lua as a library.
But as soon as I send a message I retrieve the following error message:
attempt to index global 'json' (a nil value)
The code that causes the error is the following:
json.encode({ {
["embeds"] = {
["description"] = text,
["author"] = {
["name"] = ply:Nick()
},
},
} }),
The complete code:
AddCSLuaFile()
json = require("json")
webhookURL = "https://discordapp.com/api/webhooks/XXX"
local DiscordWebhook = DiscordWebhook or {}
hook.Add( "PlayerSay", "SendMsg", function( ply, text )
t_post = {
content = json.encode({ {
["embeds"] = {
["description"] = text,
["author"] = {
["name"] = ply:Nick()
},
},
} }),
username = "Log",
}
http.Post(webhookURL, t_post)
end )
I hope somebody can help me
Garry's Mod does provide two functions to work with json.
They are:
util.TableToJSON( table table, boolean prettyPrint=false )
and
util.JSONToTable( string json )
There is no need to import json and if I recall correctly it isn't even possible.
For what you want to do you need to build your arguments as a table like this:
local arguments = {
["key"] = "Some value",
["42"] = "Not always the answer",
["deeper"] = {
["my_age"] = 22,
["my_name"] = getMyName()
},
["even more"] = from_some_variable
and then call
local args_as_json = util.TableToJSON(arguments)
Now you can pass args_as_json to your
http.Post( string url, table parameters, function onSuccess=nil, function onFailure=nil, table headers={} )
I have a test in Postman where I do a post request and need to parse the json response
The response looks like this:
"aPIProxy" : [ {
"name" : "SFDC-UpdateLoginTime-v1",
"revision" : [ {
"configuration" : {
"basePath" : "/",
"steps" : [ ]
},
"name" : "1",...some attributes}]
and i need to get something like :
"name" : "SFDC-UpdateLoginTime-v1"
"name" : "1"
for a multiple occurrence json file.
The below postman script might help you.
var jsonData = JSON.parse(responseBody);
var jsonNamesData = jsonData.aPIProxy;
console.log(jsonNamesData);
var parsedData = "";
for(var i=0;i<jsonNamesData.length;i++){
parsedData = parsedData +"\"name\" : \"" +jsonNamesData[i].name+"\", ";
console.log("\"name\" : \"" +jsonNamesData[i].name+"\"");
}
console.log(parsedData);
postman.setEnvironmentVariable("parsedNamesResponse", parsedData); // updating parsed data to the environment variable parsedNamesResponse
You could capture multiple 'name' properties using the _.map() function of Lodash, which is a built it module on the native application. I've had to modify what you need slightly as the name key would have been a duplicate.
const result = _.map(pm.response.json().aPIProxy, data => ({
name: data.name,
revisionName: data.revision[0].name
}))
pm.environment.set("response", JSON.stringify(result))
This would then store all the values in an environment variable for you to use elsewhere in another request.
You should first parse the response using JSON.parse, then you can iterate on the parsed object like:
var resObj = JSON.parse(pm.response.text())
for(var i=0; i< resObj.length; i++) {
console.log("name: "+ resObj[i].name);
}
I am getting a strange unexpected token error trying to parse a JSON file using node. I have tested the code with 2 files that look identical. I used a code compare tool to do a comparison and they do appear identical. However, when I try to parse them, one gets the error and the other does not. The file that does not work is being generated from a PowerShell script. The one that does work was manually created. I am baffled. One thing I noticed that is different about them when I write the json out to the console is, the one that does not work has a ? at the beginning.
The json from the file that does not work:
data = ?{ "stack_name": "perf-a", "parameters": { "StackSet": "b", "MonitoringEnableAutoscalingAlarm": "True", "MachineConfigEnvironment": "Perf", "AppEnvironmentType": "perf", "StackInRotation": "True", "MonitoringEnableNotificationOnlyAlarms": "False", "AMIImage": "ami-123456789" }, "tags": { "CostCenter": "12345", "Owner": "test#test.com" }, "cft_file":
"cft/cft.json"}
The json from the file that does work:
data = { "stack_name": "perf-a", "parameters": { "StackSet": "a", "MonitoringEnableAutoscalingAlarm": "True", "MachineConfigEnvironment": "Perf", "AppEnvironmentType": "perf", "StackInRotation": "True", "MonitoringEnableNotificationOnlyAlarms": "False", "AMIImage": "ami-123456789" }, "tags": { "CostCenter": "45229", "Owner": "test#test.com" }, "cft_file": "
cft/cft.json"}
The code I am using for testing is:
var envFile = "perf2.json";
var fs = require('fs');
console.log('envFile = ' + envFile);
fs.readFile(envFile, 'utf8', function (err, data) {
if (err) {
console.log('error reading variables file');
throw err;
}
try {
var JsonData = JSON.stringify(data);
console.log('JsonData = ' + JsonData);
data = data.replace(/\\n/g, "\\n")
.replace(/\\'/g, "\\'")
.replace(/\\"/g, '\\"')
.replace(/\\&/g, "\\&")
.replace(/\\r/g, "\\r")
.replace(/\\t/g, "\\t")
.replace(/\\b/g, "\\b")
.replace(/\\f/g, "\\f")
.replace(/\\0/g, "")
.replace(/\\v/g, "")
.replace(/\\e/g, "\\e");
data = data.replace(/[\u0000-\u001F]+/g, "");
console.log('data = ' + data);
var cftVariables = JSON.parse(data);
console.log('cftVariables = ' + cftVariables);
console.log('cftVariables stack name = ' + cftVariables.stack_name);
} catch (e) {
console.log('error parsing variables file');
throw e;
}
});
As you can see, I have also tried JSON.stringify but I lose the properties and cftVariables.stack_name becomes undefined.
This problem has been plaguing me for several days and I am now at a loss as to how to fix it.
For reference, here is the snippet of PowerShell that creates the file. The problem might be there.
$savePath = "envs/" +$filetouse + ".json"
$parameters = #{AppEnvironmentType =$AppEnvironmentType;
StackSet = $StackSet;
StackInRotation = $StackInRotation;
AMIImage = $amiid;
MonitoringEnableAutoscalingAlarm = $MonitoringEnableAutoscalingAlarm;
MonitoringEnableNotificationOnlyAlarms= $MonitoringEnableNotificationOnlyAlarms;
MachineConfigEnvironment = $MachineConfigEnvironment;
}
$tags = #{Owner = "test#test.com";
CostCenter = "45229";
}
$envcft = #{stack_name =$stack_name;
cft_file = "cft/cft.json";
parameters = $parameters;
tags = $tags;
} | ConvertTo-Json
Write-host("Saving the env file with the new amiId... ")
$envcft | Out-File $savePath -Encoding UTF8 -force
Assuming you are reading the data in from a file, once you have the string you can use the remove function to get rid of that "?".
Something like this:
s = s.replace('?','');
EDIT
since the replace did not work, try 1) either not specifying an encoding when you save the file, or 2) specify UTF16
I am having following structure currently present in my database, i am executing a service to fetch data from REST api and storing it to my database , so that i can use it to display it frequently on UI as like caching a data
db.countDetails.find().pretty()
{
"_id" : ObjectId("5670xxxx"),
"totalProjectCount" : 53,
"activeProjectCount" : 29,
"completedProjectCount" : 1,
"userCount" : 85
}
{
"_id" : ObjectId("5670ea97f14c717a903e8423"),
"totalProjectCount" : 48,
"activeProjectCount" : 41,
"completedProjectCount" : 0,
"userCount" : 123
}
My collection is going to remain same only values will be going to change, so please suggest me a way in which i can place the updated values in mongo and at the same time i can fetch data on my UI
my new values might be like
db.countDetails.find().pretty()
{
"_id" : ObjectId("5670xxxx"),
"totalProjectCount" : 23,
"activeProjectCount" : 17,
"completedProjectCount" : 1,
"userCount" : 60
}
{
"_id" : ObjectId("5670ea97f14c717a903e8423"),
"totalProjectCount" : 45,
"activeProjectCount" : 40,
"completedProjectCount" : 0,
"userCount" : 113
}
function to fetch data from REST api
def getCount(String companyName, String apiKey) {
//declaration section
List returnList = []
int totalProjectCount = 0 //variable to hold total no of projects value
int activeProjectCount = 0 //variable to hold total active projects value
int completedProjectCount = 0 //variable to hold total completed projects value
int userCount = 0 //variable to hold total active user count
String userAPIKey = apiKey //user API key for authorization
String method = 'GET' //method of request
String totalProjectURL = "https://"+ companyName + ".teamwork.com/projects.json?status=ALL" // Url to access All projects
StringBuilder out = getConnection(totalProjectURL, method, userAPIKey) //String builder to hold result
//catching result into json
JSONObject object = new JSONObject(out.toString()) //JSON object to store String in json format
totalProjectCount = object.projects.length()
String activeProjectCountURL = "https://"+ companyName + ".teamwork.com/projects.json?status=ACTIVE" // Url to access Active projects
out = getConnection(activeProjectCountURL, method, userAPIKey)
//catching result into json
object = new JSONObject(out.toString())
activeProjectCount = object.projects.length()
String completedProjectCountURL = "https://"+ companyName + ".teamwork.com/projects.json?status=COMPLETED" // Url to access completed projects
out = getConnection(completedProjectCountURL, method, userAPIKey)
//catching result into json
object = new JSONObject(out.toString())
completedProjectCount = object.projects.length()
String peopleURL = "https://"+ companyName + ".teamwork.com/people.json" // Url to access total active users
out = getConnection(peopleURL, method, userAPIKey)
//catching result into json
object = new JSONObject(out.toString())
userCount = object.people.length()
Map returnMap = [:]
returnMap.put('totalProjectCount', totalProjectCount)
returnMap.put('activeProjectCount', activeProjectCount)
returnMap.put('completedProjectCount', completedProjectCount)
returnMap.put('userCount', userCount)
addCount(returnMap, 'curo', 'countDetails')
println('project count successfully saved.')
}
function to add countDetails to mongo
def addCount(Map userMap, String dbName, String collectionName) {
try {
DB db = mongo.getDB(dbName)
DBCollection table = db.getCollection(collectionName)
table.insert(userMap as BasicDBObject)
def srvcResponseObj = [ responseStatus : "pass", responseCode : 200 ]
return srvcResponseObj
}
catch (Exception e)
{
println "Exception related to Mongo add record"
e.printStackTrace()
def srvcResponseObj = [ responseStatus : "fail", responseCode: 400 ]
return srvcResponseObj
}
}
function to fetch data from mongo
def fetchCountDetails(String databaseName, String collectionName) {
println 'inside fetch count details'
try {
DB db = mongo.getDB(databaseName)
DBCollection table = db.getCollection(collectionName)
DBCursor cursor = table.find()
Map returnCountMap = [:]
List temp = []
int cursorCounter = 0
while(cursor.hasNext()) {
Map temporaryMap = [:]
BasicDBObject doc = (BasicDBObject) cursor.next()
doc.remove('_id')
temp.add(doc)
cursorCounter++
}
returnCountMap.put('totalProjectCount', temp.totalProjectCount.sum())
returnCountMap.put('activeProjectCount',temp.activeProjectCount.sum())
returnCountMap.put('completedProjectCount',temp.completedProjectCount.sum())
returnCountMap.put('userCount',temp.userCount.sum())
if(cursorCounter>1)
println "Multiple objects found for eventID"
if(cursorCounter==0)
println "No objects found for eventID"
return returnCountMap
}
catch (Exception e)
{
println "Exception related to Mongo >> fetchUserDetails"
e.printStackTrace()
def srvcResponseObj = [ responseStatus : "fail", responseCode: 400 ]
return srvcResponseObj
}
}
now i am making request to REST api after fixed amount of interval and my response gets changed in terms of values, but if i call the add function again and again my documents get duplicated in mongodb and my expected result is that my new values gets reflected in mongodb