Unable to tap into object fields of Json post data in Nodejs - node.js

I am reading the sent, post data to my Nodejs using :
console.log(req.body.order)
It prints the following data in my console:
{res_key: kshdkjfh9827349sjdhf, auth_Key: ksjdhfkjs928374sdjkhf923847, customer_id: f, payment_mode: f, getMenuURL: dataurl, orderUID: dfjkh987, has_paid: 0, delivery_discount: 0, menuOrderData: [{menu_id: 244, menu_price: 4.5, item_name: Cacik (v), menu_quantity: 1, topingsOrder: []}, {menu_id: 240, menu_price: 5, item_name: Marinated Olives (v), menu_quantity: 1, topingsOrder: [{id: 708, name: Water, optional_fee: 2.00}, {id: 710, name: Coke Zero, optional_fee: 2.00}]}, {menu_id: 241, menu_price: 8.5, item_name: Mixed Pickles (v), menu_quantity: 1, topingsOrder: []}]}
My aim is to calculate the total for all items in this data so I would like to tap into it for example, I would like to tap into res_key using:
const data = req.body.order
const res = data['res_key']
Currently I am unable to read any parameter. Need help resolving this please.
My nodejs app settings are:
app.use(express.urlencoded({extended:true})); app.use(express.json());

Related

How can i manage images dynamically using pdfkit in nodejs

Q : i wanted to manage images dynamically using pdfkit in nodejs. and also i want to addPage if images not fitted in current page.
Code :
const doc = new PDFDocument({
size: 'letter'
});
function photographs(doc) {
arr = [1, 2, 3, 4, 5, 6, 7]
doc
.fillColor('#1c5695')
.fontSize(10)
.font('Helvetica-Bold')
.text('PHOTOGRAPHS', 10, doc.y, {
width: 300,
align: 'left'
})
arr.forEach((element, i) => {
doc.image('images/pdflogo.png', {
align: 'center',
fit: [100, 100]
})
});
}
so my question is how to manage x and y position of image , so it'll manage space dynamically.
e.g first 6 img set into 1st row then rest will set on 2nd row and so on..

Can't extract JSON from API response - Google Cloud Vision API (Node.js library)

This is probably a simple JSON issue but I am struggling to extract data from the text detection response using the Google Vision API on Node.js
The response I am getting looks like JSON data to me (here is a sample of the raw response as a string):
[{webDetection: null, logoAnnotations: [], context: null, safeSearchAnnotation: null,
fullTextAnnotation: {pages: [{blocks: [{blockType: TEXT, paragraphs: [{words: [{symbols:
[{boundingBox: {normalizedVertices: [], vertices: [{x: 568, y: 0}, {x: 601, y: 1}, {x:
600, y: 84}, {x: 567, y: 83}]}, property: {detectedBreak: null, detectedLanguages:
[{languageCode: en, confidence: 0}]}, confidence: 0.9900000095367432, text: B},
{boundingBox: {normalizedVertices: [], vertices: [{x: 615, y: 0}, {x: 640, y: 0}, {x: 639,
y: 83}, {x: 614, y: 83}]}, property: {detectedBreak: null, detectedLanguages:
[{languageCode: en, confidence: 0}]}, confidence: 1, text: a}, {boundingBox:
{normalized...
However when I try and parse it as follows, I am getting an error.
const jsonData = response[0].fullTextAnnotation;
const textAnnotation = JSON.parse(jsonData);
Error: SyntaxError: Unexpected token o in JSON at position 1
Any ideas what I am doing wrong and how I can extract the data correctly?
Update
I've tried reading the data as arrays and maps which doesn't work with regular for loops, but does if I use an int loop e.g.
Doesn't work:
const fullTextAnnotation = response[0].fullTextAnnotation;
const pages = fullTextAnnotation.pages;
const allBlocks = [];
for (var page in pages) {
const blocks = page.blocks;
for (var block in blocks) {
allBlocks.push(block);
}
}
Does work:
const fullTextAnnotation = response[0].fullTextAnnotation;
const pages = fullTextAnnotation.pages;
const allBlocks = [];
for (var i = 0; i<pages.length;i++) {
const blocks = pages[i].blocks;
for (var j = 0; j<blocks.length;j++) {
allBlocks.push(blocks[j]);
}
}
When I use the regular for loop I get an error:
Property 'blocks' does not exist on type 'string'.
When I use the int loop, the blocks property is properly shown as:
const blocks: vision.protos.google.cloud.vision.v1.IBlock[]
This is something I can deal with I guess, however I am definitely curious what is going wrong, because it took a lot of guessing to find the workaround.
It's hard to tell without the full string, and without the previous code, but it looks like you might be grabbing the fullTextAnnotation before you are parsing the string. I would suggest trying to parse response or response[0], and then assign fullTextAnnotation to the textAnnotation variable.
If you could share a console.log() of response, response[0], the respective JSON.parses() for those, and then possibly the unparse response[0].fullTextAnnotation, that would definitely help us diagnose the issue!

How many nested options can node-red handle?

I was wondering if there is a maximum addressing depth for json formatted files in node-red.
For instance, I have a message like this
{ topic: 'i/devices/i/up',
payload:
{ payload: 'oo',
port: 2,
counter: 54,
metadata:
[ { frequency: 868.3,
datarate: 'SF12BW125',
codingrate: '4/5',
gateway_timestamp: 4201744244,
channel: 1,
server_time: '2016-07-01T09:50:39.725658999Z',
rssi: -63,
lsnr: 8.2,
rfchain: 1,
crc: 1,
modulation: 'LORA',
gateway_eui: 'oo',
altitude: 0,
longitude: 0,
latitude: 0 } ] },
qos: 2,
retain: false,
_msgid: '81960b41.7e69f8',
metadata: <Buffer 00> }
if I wan to get metadata option, I was addressing it within a function in node red like
msg.payload.rssi = msg.payload.metadata["rssi"];
return msg;
However, when I attach a debug function to it, I don't get the rssi value that I want, what am I doing wrong? Cannot that field be addressed like that?
Thanks in advance
regards
There is no limit to the depth of a JSON object you access.
You've missed out an array index out of the selector.
What you need is:
msg.payload.rssi = msg.payload.metadata[0].rssi;
return msg;
This is because the metadata object is an array so could hold multiple instances of the metadata objects.
Also be aware that the debug tab in the Node-RED editor will truncate longer objects, if you need to see the whole object it is easiest to check the "output to console" box and the whole message will be printed to the console as well.

Multiline unbuffered code in jade templates

I am trying to write a template that renders a double indexed array. So I started writing this:
- var grid = [[1, 0, 1], [0, 1, 0]];
each row in grid
each cell in row
if cell
span x
else
span o
but this is not how I want to write my array
I want to write it like this:
- var grid = [[1, 0, 1],
[0, 1, 0]];
This doesn't work because jade is already out of the inline javascript
- var grid = [[1, 0, 1],
- [0, 1, 0]];
This doesn't work because jade considers those two incorrect lines instead of one line
How can I make it work?
Update: Multiline defs are now working for me using Jade 1.11.0. Even nested JSON now works like a charm.
-
projects = [{
title: "Project 1",
classname: "project1",
slides: [{
title: "Slide 1"
img: "images/hello.png"
},{
title: "Slide 2"
img: "images/world.png"
}]
}, {
title: "Project 2",
classname: "project2",
slides: [{
title: "Slide 3"
img: "images/fun.png"
},{
title: "Slide 4"
img: "images/things.png"
}]
}]
EDIT: Yay, these are real! Go check out the other answer on how to pull this off.
Sadly, this is currently not possible in Jade. TJ (the maintainer) has stated that he does not care about this, but would welcome a feature request. https://github.com/visionmedia/jade/issues/796
Fortunately, you can declare the array in your JS file and pass it as a variable to Jade.

Nested arrays in Mongoose

In the collection I'm working on, a document looks like this:
{
name: 'Myname',
other: 'other',
stuff: [
['something', 12, 4, 'somethingelse'],
['morestuff', 2, 4, 8],
['finally', 12, 'again', 58],
]
}
I wrote this Mongoose schema to access it:
var MyDocSchema = new Schema({
name: String,
other: String,
stuff: [],
});
When I query a doc, everything works well, the output shown in the console is right. But when, I try to do console.log(myDoc.stuff), I got the following:
['something', 12, 4, 'somethingelse', 'morestuff', 2, 4, 8, 'finally', 12, 'again', 58]
instead of
[
['something', 12, 4, 'somethingelse'],
['morestuff', 2, 4, 8],
['finally', 12, 'again', 58],
]
What am I doing wrong? Thank you for your help!!
Disclaimer: This response is pretty dated, 2012! It might not be the most accurate.
From the Mongoose documentation.
http://mongoosejs.com/docs/schematypes.html: Scroll down to the Array section:
Note: specifying an empty array is equivalent to [Mixed]. The
following all create arrays of Mixed.
Details on what that means is in the Mixed section right above the Array section.
Here's what you need to do.
Define a schema for the embedded documents:
var Stuff = new Schema({
name: String,
value1: Number,
...
});
Use that instead of an empty array []:
var MyDocSchema = new Schema({
name: String,
other: String,
stuff: [Stuff],
});

Resources