Parsing a URL query object in node.js - javascript

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.

Related

In node.js how to extract uid from returned facebook providerData json array?

I've got my users signing in with facebook and that gets stored in firebase auth. In index.js i've got an onCreate function that stores some facebook related data in firestore.
When i log to cloud functions console event.data.providerData I get this:
[ { displayName: 'xxxx xxxxx',
photoURL: 'https://scontent.xx.fbcdn.net/v/t1.0-1/p100x100/xxxxxxxxx_439xxx336xxxxxx.jpg?oh=bcxxxxxxxxxxx431ce&oe=xxxx4xxx3',
providerId: 'facebook.com',
uid: 'xxxxx725xxxxxx80' } ]
In my index.js file i've set this as
const providerData = event.data.providerData;
This always confuses me and i've read about it a lot.
These are my questions:
Is this a javascript object? Or a JSON object? Or a JSON array?
Does this need to be parsed? eg. JSON.parse(event.data.providerData)? What is JSON.parse actually doing?
To get access to the uid I have tried:
providerData[3]
providerData.uid
providerData["uid"]
providerData['uid']
JSON.parse(providerData) - and then all the above again
var obj = JSON.parse(providerData);
console.log( obj.uid );
I know there are plenty of posts out there re: similar topics and I think i've read a lot of them.
Thanks.
It's an array containing a JSON object at index 0.
The javascript interpreter is automatically parsing Valid JSON as a Javascript object.
Knowing that, you can now access directly the properties of your object like this:
providerData[0].displayName
providerData[0].photoURL
providerData[0].providerId
providerData[0].uid // <-- Your use case

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.

Send javascript array object to ashx

I have an array of objects in javascript and I like to send this object to the server in a post request to ashx handler
I'm sending the information with this script:
var filtersArray = [{id:1, val:"filter1"}, {id:2, val:"filter2"}];
var object = {filters: filtersArray, id: 123, name: "object"};
$.post('handler.ashx', jQuery.param(object), function () {
//do some stuff
});
I can see in the chrome console the network params
Form Data
filters[0][id]:1
filters[0][val]:filter1
filters[1][id]:2
filters[1][val]:filter2
id:123
name:object
And in the handler I want to retrieve the parameter filter as an array, list or something.
I tried to do this: context.Request("filters[]") but the response is Nothing to retrieve the value I have to context.Request("filters[0][id]")
But this is not useful because the size of the list could be different in each request and with this solution I should have to add a parameter with the size and iterate parameters with this number.
Another option will be transfor to a JSON object and later deserialize the object in the server. But I prefer to not do that.
There is any other way to do this?

Sails how to transform string type in array to json

I have a simple REST application built in Sails and I want to save the correct data in a model attribute of type array.
Route to post
http://localhost:1337/locations/create?name=savassibeer&locations={latitude:23789472398.2344,longitude:2734637892.56756756}&locations={latitude:22.2344,longitude:2562.56756756,date:2014-02-15T11:00:00}
The result
{
name: "savassibeer",
locations: [
"{latitude:23789472398.2344,longitude:2734637892.56756756}",
"{latitude:22.2344,longitude:2562.56756756,date:2014-02-15T21:49:23.084Z}"
],
createdAt: "2014-02-15T21:49:23.084Z",
updatedAt: "2014-02-15T21:49:23.084Z",
id: "52ffe0e345d19ec72b4fac77"
}
How can I transform the strings in locations to a valid JSON Object and save it?
You're not going to be able to do this using URL shortcuts (i.e. hitting /locations/create in the browser). They're not designed to do type-guessing. If you want to save data this way, the answer is to write a custom create action in your Locations controller that will 1) validate the locations data as #marionebl mentions above, and 2) set the locations attribute as a Javascript array.

Getting started with extJS

I don't get what I'm doing wrong.
I'm trying to populate a form from a JSON string from the server and it doesn't work. I get nothing at all back. I examine the object and it's undefined. I've been beating my head against the wall for 3 days now. I need a simple example that works and I'll build from there.
Here's the simple example that I've been trying to use:
var messages = new Ext.data.JsonStore({
url: '/user/' + user_id,
method: 'GET',
root: 'user',
fields: [
{name: 'user_id'},
{name: 'first_name'}
],
listeners: {
load: messagesLoaded
}
});
messages.load();
function messagesLoaded(messages) {
console.log(messages);
}
Here's my JSON string:
{"success":"true","user":{"user_id":"2","first_name":"Test","last_name":"Test","email":null,"password":null,"city_id":"6379","birth_date":"2009-06-09","gender":"F","created_on":"2009-06-01 17:21:07","updated_on":"2009-06-14 17:20:14","active":"Y","cuisine_id":null}}
I really don't see what I'm doing wrong, but my JSON string isn't loading. Thanks!
Ok so you're almost there, but one problem. The root ("user" in this case) has to be an array. Even if it's an array with only 1 object. Ext.data.JsonReader (the default reader for a Ext.data.JsonStore) only accepts an array of results.
So your javascript looks just fine, but the JSON object returned by the server needs to look more like this.
{
"success":"true",
"user": [{
"user_id":"2",
"first_name":"Test",
"last_name":"Test",
"email":null,
"password":null,
"city_id":"6379",
"birth_date":"2009-06-09",
"gender":"F",
"created_on":"2009-06-01 17:21:07",
"updated_on":"2009-06-14 17:20:14",
"active":"Y",
"cuisine_id":null
}]
}
One more thing, consoloe.logging your store object will produce something like [Object] in Firebug... not too useful. You should either console.dir it, or log your actual data instead.
One comment about loading your form, once you get past loading your JSON (even though this example does not show that). Make sure your form is actually rendered before trying to load it with data, e.g. if trying to use something like form.loadRecord. Otherwise you'll end up with an empty form and no errors.

Categories

Resources