I have the next response:
{
"Status": 200,
"Email": "aristos#gmail.com",
"Values": "[\"{\\\"name\\\":\\\"John\\\",\\\"age\\\":30,\\\"ids\\\":[ \\\"123445\\\", \\\"2345456\\\", \\\"42346\\\" ]}\"]"
}
I want to fix this part:
"Values": "[\"{\\\"name\\\":\\\"John\\\",\\\"age\\\":30,\\\"ids\\\":[ \\\"123445\\\", \\\"2345456\\\", \\\"42346\\\" ]}\"]"
So it looks better like this:
{ Status: 200,
Email: 'aristos#gmail.com',
Values: '{"name":"John","age":30,"ids":[ "123445", "2345456", "42346" ]}' }
I'm using node js.
var result={Status: 200,
Email: req.body.email,
Values: req.body.values};
The request is :
email:aristos#gmail.com
values:{"name":"John","age":30,"ids":[ "123445", "2345456", "42346" ]}
a post call
Regards
If you need to use req.body.values is better to use the JSON.parse() method like this:
var val = JSON.parse(req.body.values);
And then your final response String should be stringify using the JSON.stringify() method:
var result={Status: 200,
Email: "email#example.com",
Values: val};
const response = JSON.stringify(result);
Please take a look of this jsfiddle.
Not sure why your data is wrapped into array and stringified, but that's another story.
So, you need to parse a json string, and get 1st array element. Like this:
const response = {
"Status": 200,
"Email": "aristos#gmail.com",
"Values": "[\"{\\\"name\\\":\\\"John\\\",\\\"age\\\":30,\\\"ids\\\":[ \\\"123445\\\", \\\"2345456\\\", \\\"42346\\\" ]}\"]"
};
// now it's parsed and unescaped like - {"name":"John","age":30,"ids":[ "123445", "2345456", "42346" ]}
const values = JSON.parse(response.Values)[0];
response.Values = values;
// From now 'response' object will be as you want
Related
I'm new to Node.js/AWS lambda. Ive successfully created several documentClient QUERY functions that return a single or multiple item JSON Document in this format:
[
{
"name": "andy",
"color": "purple",
"snack": "oreos"
}
]
When I use documentClient GET and get back my single record its in THIS format, which is not playing well with the client code (apple / ios swift)
{
"name": "andy",
"color": "purple",
"snack": "oreos"
}
I'm hopign i can change the format returned from documentClient.get() to include the fill JSON document format including leading and trailing brackets .. []
I am a node.js & aws.lambda and documentClient novice, so apologies if this is a very basic question....
provided in above text
If I understood well, you're receiving an object instead of a array.
You can use the scan function to retrieve an array of results:
var params = {
TableName : 'Table',
FilterExpression : 'Year = :this_year',
ExpressionAttributeValues : {':this_year' : 2015}
};
var documentClient = new AWS.DynamoDB.DocumentClient();
documentClient.scan(params, function(err, data) {
if (err) console.log(err);
else console.log(data);
});
Or you can transform the result to array:
const document = await documentClient.get({
TableName: "table-of-example",
Key: {
id: "id-of-example"
}
});
return [data]
Please read the document to understand more how the document dynamodb sdk works: https://docs.aws.amazon.com/AWSJavaScriptSDK/latest/AWS/DynamoDB/DocumentClient.html#scan-property
I have an object like this:
const querystring = require('querystring');
let data = {
name: 'Bill',
hobbies: ['Painting', 'Running']
}
If I encode the object like this:
console.log(querystring.encode(data));
I get this:
name=Bill&hobbies=Painting&hobbies=Running
Then when I decode it:
console.log(querystring.decode(querystring.encode(data));
It comes back perfectly like this:
{
name: 'Bill',
hobbies: ['Painting', 'Running']
}
However if I pass an object with array data that has only one item in it like this:
let data = {
name: 'Bill',
hobbies: ['Painting']
}
When I encode / decode it:
console.log(querystring.decode(querystring.encode(data));
This comes back:
{
name: 'Bill',
hobbies: 'Painting'
}
Notice how it converts the array to a single string, rather than an array with a single item.
Is there anyway around this limitation with querystring? Or is there another module that handles this better? I've been looking around and can't find anything.
I cannot get quickreplies to work in node-wit messenger.js example.
I tried may things including:
1) Updated this line of code Our bot actions (messenger.js):
const actions = { send({sessionId}, {text,quickreplies})
2) And Updated this line of code Our bot actions (messenger.js):
return fbMessage(recipientId, text,quickreplies)
3) Updated my custom action in messenger.js :
getWelcome({context, entities})
{
context.welcome = "how are you. Please select from the options below";
context.welcome.quickreplies = [
{
title: 'Choice A',
content_type: 'text',
payload: 'empty'
},
{
title: 'Choice B',
content_type: 'text',
payload: 'empty'
},
]
return context;
},
4) I tried so many permutations. I cant get it to work with node-wit messenger.js example. The quick repliess are not displayed I searched and read all documentation
5) Can you help with this and also exactly how to retrieve the quick reply selected in messenger.js
Thanks
Sorry if it is late, but I guess you were looking for this:
send(request, response) {
const {sessionId, context, entities} = request;
let {text, quickreplies} = response;
if(text.substring(0,6) === IDENTIFY_PAYLOAD){
text = text.substring(6); // It is a payload, not raw text
} else {
text = {"text": text};
}
if(typeof quickreplies !== "undefined"){
text.quick_replies = response.quickreplies
.map(x => { return {
"title": x, "content_type": "text", "payload": "empty"}
});
}
}
What I did was sending a payload with a string that identifies it is not raw text (That's why I use an identifier for a payload), then in the send action I receive the two parameters request and response, and I get their attributes. Finally, I convert the payload params using a routine which I find on internet and that in fact works well to map the quick replies.
How can i get JSON objects in the following case:
Here is my post request:
var articles = client.post("http://host:port/path", args, function (data, response) {
// console.log(xml.parseBuffer(data))
console.log(data.toString('utf8'));
// return xml.parseBuffer(data);
});
result of data.toString('utf8') look like:
<WebServiceResponse>
<page>
...
</page>
<articleDataList>
<articleId>
<idArticle>100000</idArticle>
<index>test</index>
</articleId>
<goodType>test</goodType>
<idAttributeSubject>100001</idAttributeSubject>
<identyfiable>false</identyfiable>
<isActive>true</isActive>
<isGoodSet>false</isGoodSet>
<longName>test</longName>
<translationSubjectId>
<idTranslationSubject>100408</idTranslationSubject>
</translationSubjectId>
<unitCode>szt</unitCode>
<vatRate>0.2300</vatRate>
</articleDataList>
<articleDataList>
...
</articleDataList>
<articleDataList>
...
and xml.parseBuffer(data) looks:
{ name: 'articleDataList', childs: [Object] },
I need put into articles objects with only: idArticle, index and shortName
Is there any easy way?
In this output:
{ name: 'articleDataList', childs: [Object] }
Object represents javascript object that you need to stringify like this: JSON.stringify(Object)
Or you should convert this whole Buffer to string first, and then convert to JSON or javascript object:
xml.parseString(data.toString('utf8'))
I've got the following code, but it doesn't seem to work:
var post_req = {
array: [
[ {
param1: 'something',
param2: 123
} ],
[ ],
[ ],
[ {
param2: 'something',
param4: 1234,
param1: 'hello'
} ]
]
};
var data_send = querystring.stringify(post_req);
var request = client.request('POST', '/', headers);
request.end(data_send);
and
if( req.method == 'POST' ) {
req.addListener('data', function(chunk)
{
POST = querystring.parse(chunk);
console.log(POST);
}
}
I end up with 5 sub-arrays, corresponding to the 5 parameters in the objects but with extra '][' characters in their names:
{ array:
[ { '][param1': 'something' }
, { '][param2': '123' }
, { '][param2': 'something' }
, { '][param4': '1234' }
, { '][param1': 'hello' }
]
}
There is a new node package that fixes this: "npm install qs".
https://github.com/ljharb/qs
"query string parser for node supporting nesting, as it was removed from 0.3.x, so this library provides the previous and commonly desired behaviour (and twice as fast)"
If anyone can tell me why it was removed from 0.3.x, I will give you an upvote for your comment. (I want my confidence in Node.js restored.)
To confirm my comment above, node's querystring.stringify function won't handle nested arrays (at the time of writing).
You can see the source of stringify at https://github.com/ry/node/blob/master/lib/querystring.js
Note that it handles one level of arrays but it doesn't recurse. When it finds an array it uses stringifyPrimitive to encode the array's values. You can see that stringifyPrimitive doesn't handle arrays, only number, boolean and string.
As I suggested in my comment, given that you're using a POST request a better idea would be to use JSON encoding for your complex data structure.
Or use https://github.com/visionmedia/node-querystring as suggested by #FriendlyDev
Don't use querystring.parse for recreating a JSON object sent as string. Use instead JSON.parse. And use JSON.stringify instead of querystring.stringify
querystring is useful when you send parameter encoded in the url or when you post a form. But there is no point in using it if you send just one JSON object with all your data.
In your scenario I would dismiss the querystring library and use JSON library, which is already included. It would be cleaner and faster.
http://www.json.org/js.html