How to Filter JSON.parse results - javascript

I have been trying to filter the results of an API call based on my "note" value. I've been building it on Zapier and the call works but I cannot seem to find a way to make a filter function do its job (so if I replace line 19-23 with return results; then it gives me all orders from the api call). I've poured over every stack document I could find but they all end with the error result.filter not found, or a bargle error (generic error in Zapier).
const options = {
url: `https://mystorename.myshopify.com/admin/orders.json?`,
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
params: {
}
}
return z.request(options)
.then((response) => {
response.throwForStatus();
var results = z.JSON.parse(response.content);
var queryItem = "555-5555"
const filteredOrders = results.orders.filter(item => item.note === queryItem);
return filteredOrders;
});
And this is an example of my current output with return results; and no filter:
{
"orders": [
{
"note": "555-5555",
"subtotal_price": "1.00"
},
{
"note": "555-6666",
"subtotal_price": "2.00"
}
]
}
Again the goal is to filter by the value in the "note" key. So if my filter input is 555-5555 then it should return all information for that item only. I did try to use an if statement for return, stringify instead of parse, covert to array...all with needed code, but regardless of the format I find filter does not work or nothing is returned. Going to keep working on it, so if I happen to find the answer I will post that, but at this point I feel stuck.

You are trying to use the method filter in a object but filter is only available in an array so you should try to call filter in the orders array.
let results = {
"orders": [
{
"note": "555-5555",
"subtotal_price": "1.00"
},
{
"note": "555-6666",
"subtotal_price": "2.00"
}
]
}
let queryItem = "555-5555";
let newArray = results.orders.filter(function (item) {
return item.note == queryItem
})
console.log(newArray)
Updated to contain a real http call:
const url = 'http://www.mocky.io/v2/5d9466142f000058008ff6b7'
const options = {
method: 'GET',
headers: {
'Content-Type': 'application/json',
'Accept': 'application/json'
},
}
const response = await fetch(url, options)
const results = await response.json()
const queryItem = "555-5555"
const filteredOrders = results.orders.filter(item => item.note === queryItem)
console.log(filteredOrders)

You are trying to filter on results, but according to your output, you should be filtering on results.orders.
const filteredOrders = results.orders.filter(item => item.note === queryItem);

Are you getting all the orders back (all the orders with the specified filter value)?
I realized I wasn't getting back all orders and this did the trick:
`https://mystorename.myshopify.com/admin/orders.json?status=any`
Alternatively, you can query the orders with that specific note:
`https://mystorename.myshopify.com/admin/orders.json?status=any&note=` + queryItem

Related

How to return a JSON list in the following format

I am using the bubble.io plugin builder. To return a response under bubble.io's api connector, all parameters returned must have the prefix "p". In the following case, this returns the correct results for an api call.
const options = {
url: url
,method: method
,headers: {
"Content-Type": "application/json"
}
}
const response = context.request(options);
console.log(response);
/*
The model we will use
{
"mins": 5,
"price": "34823.91104827"
}
*/
var body = JSON.parse(response.body);
const {convert} = require('json-to-bubble-object');
let returnlist = []
returnlist.push( {
"_p_mins": body.mins.toString(),
"_p_price": body.price,
"_p_api_response": JSON.stringify(convert(body))
})
return {
"result": returnlist
}
This call generates the following response:
_p_api_response: "{"_p_mins":5,"_p_price":"36703.73207769"}"
_p_mins: "5"
_p_price: "36703.73207769"
What I am trying to do is use the module 'json-to-bubble-object' as returned in the _p_api_response parameter (which is a test parameter and is not actually needed) to return the data. This makes my call dynamic so I don't have to manually specify the parameters for each different api call.
Hence, I am trying to make the API call look something like this:
var body = JSON.parse(response.body);
const {convert} = require('json-to-bubble-object');
let returnlist = []
returnlist.push( JSON.stringify(convert(body))
)
return {
"result": returnlist
}
but this returns null results
_p_api_response: null
_p_mins: null
_p_price: null
can someone let me know how I can return the data generated from the convert function as a list as done in the first request? Thanks
EDIT: For clarification, the p prefix allows the response headers to be viewed in the bubble.io builder, as seen in the below image.
I dont have enough reputation to comment but
I am unable to repro your problem.
You can view my repro here:
https://runkit.com/runkitname/so-a-nodejs
const {convert} = require('json-to-bubble-object');
var body = {
"mins": 5,
"price": "34823.91104827"
}
body.api_response = JSON.stringify(convert(body))
let returnlist = []
returnlist.push(convert(body))
console.log({"result": returnlist})
console
{
result: [
{
_p_mins: 5,
_p_price: '34823.91104827',
_p_api_response: '{"_p_mins":5,"_p_price":"34823.91104827"}'
}
]
}

How to parse json in react native

I'm working on react native project, and i'm calling API and extracting data from it , the data is succesfully extracted but I want to take arguments from the extracted data and I did'nt know how
This is the code for fetching api :
Axios({
url: '/Authentification',
method: 'get',
baseURL: 'http://smart.netrostercloud.com/api',
transformRequest: [
function (data, headers) {
return data;
},
],
transformResponse: [
function (data) {
// console.log(data);
setData3(data);
},
],
headers: {
Authorization: 'Basic UxvwJc1GWjkOCyZoIHGuCD05gDUB72sqrgK30FgILho=',
},
});
console.log(data3);
I've used data3 to extract the data in my main function so it can be visible.
This is the data :
I want to take CompanyCode,UserName,Password,FirstName and LastName
Firstly : axios its n asynchronous function, so its return a promise,
Actually i dont prefere use this patern in simple api call l, but its good way if you know this concept and use oop like create instance of axios to reusable and cancel connectiin when component will unmount.
Fot this i prefere use this way
Const getUserData= async () =>{
try {
Const {data} = await axios.get(baseurl+route, headers , options)
data & & SetData({username:data. User. Username,........... } )
Dosomthing...
}
Catch(error) {
Dosomthing...
}
Before you storing data into data3 you need to stringify the data like this setData3(JSON.stringify(data));
and then try this:
if (data3) {
const COMP_NAME = data?.user?.CompanyCode;
const USER_NAME = data?.user?.UserName;
CONST FIRST_NAME = data?.user?.FirstName;
CONST LAST_NAME = data?.user?.LastName;
}

invaild function while using express.js

invaild function while using express.js
in my app.js where express is installed some of the functions are not working
app.get("/",(req,res)=>{
const options = {
"method": "GET",
"hostname": "alexnormand-dino-ipsum.p.rapidapi.com",
"port": null,
"path": "/?paragraphs=1&words=1&format=json",
"headers": {
"x-rapidapi-key": "dcc30b2b2fmshac3b7e241a8fc6cp1061bdjsn8937e7e638cb",
"x-rapidapi-host": "alexnormand-dino-ipsum.p.rapidapi.com",
"useQueryString": true
}
};
https.get(options, function (response) {
response.on("data",function(data){
const dinoData = JSON.parse(data);
const b = dinoData.replace('[', '')
console.log(b);
})
})
res.render("main");
})
emphasized text
enter image description here
dinoData.replace('[', '') is incorect because of dinoData is not a string but object
This is because you are doing a replace on an object (here - dinoData.replace('[', '')), you would either have to iterate over the keys like below and check the values, or also check the keys etc. Or you could maybe remove the data you dont want before parsing the string to an object, but I would recommend the former and not the latter as you may corrupt the JSON.
const myJson = JSON.parse('*valid-json-goes-here*')
for (const key in myJson) {
// Might not be what you want, just an example
myJson[key] = myJson[key].replace('[', '')
}

How do I pull a nested object out of an array with an api request returned json?

I have an API that I am calling to return a query. This query's format cannot be changed to be easier to manipulate. It has a nested array within it that I need to associate with the data from the higher levels.
Specifically, I am trying to pull the higher level id field and and the "value" field within "column_values" and associate them with one another preferably within a new array. I feel like the answer is here but I just can't grasp how to pull the data in the correct format and associate it together. Most of the comment lines can probably be ignored, they are my other attempts at making the syntax work correctly. Sorry about the mess. I'm really new to this.
const axios = require('axios')
const body = {
query: ` query {boards(ids:307027197) {name, items {name id column_values(ids:lockbox_) {title id value text}}}} `,
}
console.log("Requesting Query....");
function getApi (callback){
setTimeout(function() {axios.post(`https://api.monday.com/v2`, body, {
headers: {
MY_API_KEY_DATA
},
})
.catch(err => {
console.error(err.data)
})
.then(res => {
var queried = res
var array = queried.data.data.boards[0].items
//console.log(queried)
//console.log(array)
console.log(array.length)
//console.log("Total Items:", array.length)
var i;
for (i = 0; i < array.length; i++){
callback(queried.data.data.boards[0].items)
//callback([(queried.data.data.boards[0].items[i].column_values[0])])
}
}, 0);
})
};
getApi(callback => {
console.log(callback)
//console.log(parsed)
//output for above
//{"name":"address","id":"1234","column_values":
//[{"title":"Lockbox#","id":"lockbox_","value":"\"31368720\"","text":"31368720"}]}
//console.log(JSON.parse(parsed))
//output for above
//[
// {
// name: 'address',
// id: '353428429',
// column_values: [ [Object] ]
// }
//]
});
setTimeout(function() {
console.log("Query Returned")},1000);
From your data, column_values is an array with objects in it. For an array, you will have to access it with the key. For your case, if your data is like
var data = {
"name":"address",
"id":"1234",
"column_values": [{"title":"Lockbox#","id":"lockbox_","value":"\"31368720\"","text":"31368720"}]
}
You can access the id of column_values as data.column_values[0].id

Converting array of objects into array of strings

I'm working on an app where I need to pass an array of strings to a backend service something like
const ids = [];
for (let i = 0; i < pIds.length; i++) {
ids.push(pIds[i].id);
}
// pIds is an array of objects [{id: 2, name: 'dd'}]
this.webClient = new Frisbee({
baseURI: `${Secrets.url_host}/api/v1`,
headers: {
Accept: 'application/json',
'Content-Type': 'application/json',
},
});
getData({ continuation = 1, q = '', ids = '' }) {
return this.webClient.get('/whatever', {
body: {
'platform_ids': ids,
},
}).then(getContent);
}
after running this code if get an array of ids [2,3] for example
but when I pass it to the backend (ruby on rails ) it arrive like that
[{"0"=>"1", "1"=>"2"}]
What can I do to get it as ["1", "2"]? I've tried many solutions but nothing works.
I couldn't solve it , so i changed my backend to accept string with "," and parsing it to array in the backend .
for example
const ids = {id: 3, id: 4};
const idsForBackend = ids.map(id => id.id).join();

Categories