extract specific part of API response to JSON object in Javascript - 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.

Related

Reading a JSON response in Javascript

I'm making an ajax post request to a super simple python function that takes a student's name and spits out a url that corresponds to it. Currently, the Python function passes this back in json and looks like so when console.log(JSON.stringify(response)) is called:
{"readyState":4,"responseText”:”\ {\”studentURL\”: \”https://prepacademy.jackjohnson.com\”} ”,”responseJSON”: {“studentURL”:”https://prepacademy.jackjohnson.com”},”status":200,"statusText":"OK"}
I was wondering how do I take this larger chunk of information and filter it so that I would only get the https://prepacademy.jackjohnson.com part?
response is a JavaScript Object of which you can access the properties using either Dot-notation or bracket-notation, like so:
let response = {
"readyState": 4,
"responseText": "\ {\"studentURL\": \"https://prepacademy.jackjohnson.com\"} ",
"responseJSON": {
"studentURL": "https://prepacademy.jackjohnson.com"
},
"status": 200,
"statusText": "OK"
};
// dot-notation
console.log(response.responseJSON.studentURL)
// bracket-notation (allows for computed paths)
console.log(response["responseJSON"]["studentURL"])
response.responseJSON.studentURL

Unable to get a value from a json after node fetch in javascript

For My API GET operation, I use node fetch and my code is
var fetch = require('node-fetch');
const HttpProxyAgent = require('http-proxy-agent');
const HttpsProxyAgent = require('https-proxy-agent');
fetch('https://threemashery.rb.ipdesign.info/cit1/apigw/tibs/nbrmgmt/NumberManagementService/v1/RetrieveListDNForSelection?apikey=5w8anhcabembfp7tne67rhk8&userID=cpacadm&quantity=2&operatorId=3UK&orderNumber=ORD12341&numberCategory=Normal', {method: 'GET', agent: new
HttpsProxyAgent('http://10.10.104.4:50683') })
.then(resRaw=>{
return resRaw.text();
})
.then(resJson=>{
console.log(resJson);
console.log(resJson.Header);
})
And below are my both console log outputs
{"Header":{"ActivityName_T":"AS_DNLogicalResource_NM","MsgType_T":"RESPONSE","msgName":"Error occured while processing request for List DN","Source":"RetrieveListDNLogicalResourceNM","ActivityStatusEnum_T":"FAILURE","ActivityStatus_T":"rcFailure","Timestamp":"2018-07-26T14:45:14.009Z","ProviderInfo":[{"name":"b08359a6-dea1-4e34-9c47-8d5971e1a9dd1532616302405","valueType":"rcFailure","description":"Order is being modified.","Value":{"CharacteristicValue":[{"value":"FAILURE"}]}}]},"Payload":{"NotificationDetails":[{"errorCode":"rcFailure","errorDescription":"Order is being modified."}]}}
undefined
Why am I getting as undefined, while I try to take the first element? someone please help me.
Even I tried the below
console.log(resJson);
let res=JSON.stringify(resJson);
console.log(res);
But I am getting like
{"Header":{"ActivityName_T":"AS_DNLogicalResource_NM","MsgType_T":"RESPONSE","msgName":"Error occured while processing request for List DN","Source":"RetrieveListDNLogicalResourceNM","ActivityStatusEnum_T":"FAILURE","ActivityStatus_T":"rcFailure","Timestamp":"2018-07-26T14:40:40.189Z","ProviderInfo":[{"name":"4463c84f-4d38-4173-8f11-3b82b2c539a51532616029573","valueType":"rcFailure","description":"Order is being modified.","Value":{"CharacteristicValue":[{"value":"FAILURE"}]}}]},"Payload":{"NotificationDetails":[{"errorCode":"rcFailure","errorDescription":"Order is being modified."}]}}
"{\"Header\":{\"ActivityName_T\":\"AS_DNLogicalResource_NM\",\"MsgType_T\":\"RESPONSE\",\"msgName\":\"Error occured while processing request for List DN\",\"Source\":\"RetrieveListDNLogicalResourceNM\",\"ActivityStatusEnum_T\":\"FAILURE\",\"ActivityStatus_T\":\"rcFailure\",\"Timestamp\":\"2018-07-26T14:40:40.189Z\",\"ProviderInfo\":[{\"name\":\"4463c84f-4d38-4173-8f11-3b82b2c539a51532616029573\",\"valueType\":\"rcFailure\",\"description\":\"Order is being modified.\",\"Value\":{\"CharacteristicValue\":[{\"value\":\"FAILURE\"}]}}]},\"Payload\":{\"NotificationDetails\":[{\"errorCode\":\"rcFailure\",\"errorDescription\":\"Order is being modified.\"}]}}"
Why am I getting as undefined, while I try to take the first element?
You said return resRaw.text() so resJson is the text of the response.
A simple string does not have a Header property.
You need to return resRaw.json() if you want to parse the response as JSON and put the resulting object into resJson.
Even I tried the below
let res=JSON.stringify(resJson);
That's going in the wrong direction. You're taking the string and then expressing it in JSON.
You need to parse the JSON into JavaScript data.

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

API Connect - 500 error when including basic Javascript

I'm trying some basic API Connect tutorials on IBM's platform (running locally using loopback) and have got completely stuck at an early point.
I've built a basic API service with some in-memory data and setter / getter functions. I've then built a separate API which takes two GET parameters and uses one of my getter functions to perform a search based on two criteria. When I run it, I successfully get a response with the following JSON object:
[{"itemId":1,"charge":9,"itemSize":2,"id":2}]
I've then tried to add a piece of server logic that modifies the response data - at this point, I'm just trying to add an extra field. I've added a Javascript component in the Assemble view and included the following code (taken from a tutorial), which I thought should modify the message body returned by the API while still passing it through:
//APIC: get the payload
var json = apim.getvariable('message.body');
//console.error("json %s", JSON.stringify(json));
//same: code to inject new attribute
json.platform = 'Powered by IBM API Connect';
//APIC: set the payload
//message.body = json;
apim.setvariable('message.body', json);
Instead of getting an extra JSON parameter ("platform"), all I get is a 500 error when I call the service. I'm guessing that I'm doing something fundamentally wrong, but all the docs suggest these are the right variable names to use.
You can't access json.platform but at that point json variable is json type. Are you sure that you can add a property to a json type variable if your json object lacks of that property? I mean: What if you first parse the json variable of json type to a normal object, then add new property, and finally stringify to json type again for body assigning purposes?
var json = JSON.parse(apim.getvariable('message.body')); //convert to normal object
json.platform = 'Powered by IBM API Connect'; //add new property
apim.setvariable('message.body', JSON.stringify(json)); //convert to json again before setting as body value
You need to get the context in some determined format, and in this function do your logic. For example if your message is in json you need to do:
apim.readInputAsJSON(function (error, json) {
if (error)
{
// handle error
apim.error('MyError', 500, 'Internal Error', 'Some error message');
}
else
{
//APIC: get the payload
var json = apim.getvariable('message.body');
//console.error("json %s", JSON.stringify(json));
if(json){
//same: code to inject new attribute
json.platform = 'Powered by IBM API Connect';
//APIC: set the payload
//message.body = json;
apim.setvariable('message.body', json);
}
}
});
Reference:
IBM Reference
You have the message.body empty, put a invoke/proxy policy before your gateway/javascript policy for example.

Display data from web service (Js, Angular)

I've been trying to display some data from a web service with no luck
I tried this
ngOnInit(){
//console.log(this._productoService.getDeudas());
this._productoService.getDeudas().subscribe(
result =>{
console.log(result.Cuotas);
}
);
}
}
and i got this error
Property 'Cuotas' does not exist on type 'Response'.
this is the data i got in the console
any ideas? thanks in advance
Response is an object and therefore you can use...
result => { result ['Cuotas']; }
... the [result ['Cuotas']] field access stands out because you use bracket notation to access the results field. If you tried to write [result.Cuotas], TypeScript would correctly complain that the Object coming back from HTTP does not have a results property. That's because while HttpClient parsed the JSON response into an Object, it doesn't know what shape that object is.
https://angular.io/guide/http

Categories

Resources