Taking JSON and working with individuals pieces of information within the JSON - javascript

I have an Express App that is being fed JSON data, when I req.body the data I get this:
{ '["A","07 Sep 2016","47.07","47.17","46.86","47.11","1542500"]': '' }
In the end I need to get this into my RethinkDB database, but right now I am trying to just console.log the "A" I have tried req.body[0] and it is showing undefined. I am a little confused about the fact that there are ' ' around the array. I am not sure where the : '' comes from at the end of the JSON but for now I just need the main values in the array.
FYI I am using papaParse to parse a CSV to JSON which is how this data is being sent to my express app. Then fetch is being used to send the data with 'Content-Type': 'application/x-www-form-urlencoded; charset=utf-8' as the header.

The JSON is structured differently then you think.
Your JSON:
{
'["A","07 Sep 2016","47.07","47.17","46.86","47.11","1542500"]': ''
}
so req.body[0] wont work, the key is the array which is what you need and the value is just an empty string.
should be something like this:
{
'result': '["A","07 Sep 2016","47.07","47.17","46.86","47.11","1542500"]'
}
req.body.result[0] // -> "A"

Related

How to interpret extended json data

Description of the problem
I will not write any codes as much of my problem is something linked with the knowledge to interpret some data. I am doing a project and had to use a nonsql database to store data the sampled information from a microcontroller. The chosen db was mondodb. I wrote all the code that stores the info and now i want to exhibit the date on a html page. The problem is that when i do the request using restapi to the mongodb, the json that was stored there comes in the extened json format, i.e.:
"_id": {
"$oid": "6230d05dcf81542c5aabc30b"
},
"sensor": {
"$numberDouble": "1"
}
But it should have come as the data is stored in the db:
"{
_id": "6230d05dcf81542c5aabc30b",
"sensor": 1.0
}
As you can see, the the json comes with extra information linked to the type of the variable that is stored. But i don't really know how to use that information in javascript. I would just read it for example as json.sensor.$numberDouble if i wanted to get the information about the sensor instead of json.sensor if the json was in the normal way. I don't see much of an use to the extended version. Is something i am doing wrong?
Make sure, that you Parse API response, like-
response.json()
It looks like you're getting back an EJSON response. If you want to send back standard JSON response then that should be set as the Content-Type on the server response.
function(req, res) {
data = { ... }; // Your data here
res.setHeader("Content-Type", "application/json");
res.setBody(JSON.stringify(data));
}
If you don't have control over the server side, then convert the EJSON back to plain JSON using the meteor EJSON library.

Parsing a URL query object in node.js

I need to create a function that will use an object passed in the url. The goal is to update menu items for a restaurant. The query sent will look like this:
?restId=1&posId=1&groups=…&items= [{"id":"000101","price":2500,"desc":"ארוחת ראפ","count":0,"status":0,"type":0,"group":1,"variations":[]},{"id":"000145","price":7980,"desc":"ארוחת בוקר ילדים","count":0,"status":0,"type":1,"group":1,"variations":[{"desc":"LEVEL 1","level":1,"maxNumAllowed":1,"items":[{"id":"000119","price":500,"desc":"ספריבס כבש טרי","count":0,"type":0,"group":1,"variations":[]},{"id":"000117","price":0,"desc":"פילה עוף טרי","count":0,"type":0,"group":1,"variations":[]},{"id":"000166","price":0,"desc":"שישליק הודו טרי","count":0,"type":0,"group":1,"variations":[]}]&pizzas=[{"id":"100250","desc":"מגש משפחתית","slices":4,"price":6400,"count":1,"group":3,"toppingPolicy":[{"id":"100112","desc":"תוספת גבינה","pricing":[{"slicesCount":1,"price":200},{"slicesCount":2,"price":400},{"slicesCount":3,"price":600},{"slicesCount":4,"price":800}]},{"id":"100111","desc":"ללא גבינה","pricing":[{"slicesCount":1,"price":0},{"slicesCount":2,"price":0},{"slicesCount":3,"price":0},{"slicesCount":4,"price":0}]},{"id":"100110","desc":"ללא רוטב","pricing":[{"slicesCount":1,"price":0},{"slicesCount":2,"price":0},{"slicesCount":3,"price":0},{"slicesCount":4,"price":0}]}],"discountable":true}]
When I run const queryObject = url.parse(req.url,true).query; it prints:
[Object: null prototype] {
restId: '1',
posId: '1',
groups: '…',
items: ' [{"id":"000101","price":2500,"desc":"ארוחת ראפ","count":0,"status":0,"type":0,"group":1,"variations":[]},{"id":"000145","price":7980,"desc":"ארוחת בוקר ילדים","count":0,"status":0,"type":1,"group":1,"variations":[{"desc":"LEVEL 1","level":1,"maxNumAllowed":1,"items":[{"id":"000119","price":500,"desc":"ספריבס כבש טרי","count":0,"type":0,"group":1,"variations":[]},{"id":"000117","price":0,"desc":"פילה עוף טרי","count":0,"type":0,"group":1,"variations":[]},{"id":"000166","price":0,"desc":"שישליק הודו טרי","count":0,"type":0,"group":1,"variations":[]}]',
pizzas: '[{"id":"100250","desc":"מגש משפחתית","slices":4,"price":6400,"count":1,"group":3,"toppingPolicy":[{"id":"100112","desc":"תוספת גבינה","pricing":[{"slicesCount":1,"price":200},{"slicesCount":2,"price":400},{"slicesCount":3,"price":600},{"slicesCount":4,"price":800}]},{"id":"100111","desc":"ללא גבינה","pricing":[{"slicesCount":1,"price":0},{"slicesCount":2,"price":0},{"slicesCount":3,"price":0},{"slicesCount":4,"price":0}]},{"id":"100110","desc":"ללא רוטב","pricing":[{"slicesCount":1,"price":0},{"slicesCount":2,"price":0},{"slicesCount":3,"price":0},{"slicesCount":4,"price":0}]}],"discountable":true}]'
}
My problem is that I cannot access any of the values in items. I was given this url, so I cannot change it at all. How can I parse items in order to access the values?
The value of items and pizzas are both JSON formatted strings. You have to parse them to access the contained data. This is accomplished by calling JSON.parse()
So in your case, to access items, you could do the following:
const items = JSON.parse(queryObject.items)
The only problem you have now is that items isn't actually a valid JSON string. It's missing four closing tags }]}] at the end. I'm not sure if that's a transcription error or if you're actually getting a malformed URL, but that will cause you issues if the URL in your question is accurate.

Accessing JSON data when response contains both JSON data and text

Initially the content from the server was JSON data.And I was able to access the data perfectly.
{ "status":"ok", "artifact":"weblayer-war", "version":"0.0.41-test-data", "buildtime":"test-data" }
Now the response from the server has been changed to json data + text data.
{ "status":"ok", "artifact":"weblayer-war", "version":"0.0.41-test-data", "buildtime":"test-data" }
Properties for service:
=======================
ServiceEndpoint: https://somedomain:1200/web/Servlet/SOAP/Services
Certificates: false
DocumentName: note.pdf
So whether changing the content-type to application-text and using split method is the only way we can solve this or Is there any better approach?
As mentioned in the comments, mixing JSON and pure text data is wrong (as it defeats the advantage of using standardized data format) and should be avoided. Maybe that is some kind of debug log that was accidentally included in the production code?
If not, you should read just the first line of response and parse it as JSON data, ignoring the rest, hoping for no more changes in response structure ;)
You really should overthink your API design.
What about adding the text part as part of your JSON?
{
... // your JSON properties here
"serviceProperties": { // properties for service
"ServiceEndpoint": "https://somedomain:1200/web/Servlet/SOAP/Services",
"Certificates": false,
"DocumentName": "note.pdf"
}
}

extract specific part of API response to JSON object in Javascript

I am trying to interrogate an API response from the Recognize (fashion recognition) API. The data is returned as set out below. I am trying to extract the items of attire from the following object.
Object {data: " Array↵(↵ [id] => 1309↵)↵{"Status":true,"Data":{"VufindTags":["Dress"," Purse"]}}", status: 200, headers: function, config: Object, statusText: "OK"}config: Objectdata: " Array↵(↵ [id] => 1309↵)↵{"Status":true,"Data":{"VufindTags":["Dress"," Purse"]}}"headers: function (name) {status: 200statusText: "OK"__proto__: Object
I have tried to access using data.data which returned the following as a string:
" Array
(
[id] => 1309
)
{"Status":true,"Data":{"VufindTags":["Dress"," Purse"]}}"
I then tried to use JSON.parse to extract the data from the VufindTags. That did not work.
Is there a way to convert this into a JSON Object??
Thanks for any help!!
It looks like the vufind API is giving you PHP print_r output instead of JSON. The best thing to do would be to get them to fix their API. Failing that, you can pull the JSON-ified bits out. I had some success with this:
myObj = JSON.parse(apiOutput.slice(apiOutput.indexOf('{')))
...but I wouldn't put that into an app and call it production ready, especially when the API clearly isn't giving you what it should in the first place.

req.body of post router contains new line and colon?

I would like to know how to extract the post data from req.body.
My post data is
{
name:'asdf',
completed: false,
note: 'asdf'
}
When I am trying to console it using JSON.stringify , I am getting req.body as
{"{\n name:'asdf',completed:false,note:'asdf'}":""}
I noticed that new line and colon are getting added to the req.body object. So when I am trying to filter req.body.name its returning me undefined.
I have used app.use(bodyParser.json());but still I am not getting the actual result
Hence I would like to know the following:
1. How to filter the post object?
2. Why new lines and colon are getting added to req.body object?
I found solution myself by following
req.body empty on posts
As I am testing in rest-client, The mistakes I did are,
I initially made content-type:www-form-urlencoded. Then later I made it as application/json
I didnt use quotes for key in key-value pair. so you need to pass data in raw section as
{"name":"asdf",
"completed":false,
"note":"asdf"}
Note: Though www-form-urlencoded also work, when you are passing data in form section as
name asdf
completed false
note asdf
All the parsers accept a type option which allows you to change the Content-Type that the middleware will parse.
// parse various different custom JSON types as JSON
app.use(bodyParser.json({ type: 'application/*+json' }))
// parse some custom thing into a Buffer
app.use(bodyParser.raw({ type: 'application/vnd.custom-type' }))
// parse an HTML body into a string
app.use(bodyParser.text({ type: 'text/html' }))

Categories

Resources