Fetch returning undefined after parsing with json - javascript

I am writing a JavaScipt application and am attempting to fetch data from a certain URL but am getting an undefined value. The expected value after fetching and converting it to json should result in an array. I am not sure why this is happening. I have put my code below:
let promiseResponse = fetch("some-url");
let response = await promiseResponse;
// check if there was an error in fetching the data (no error detected)
if(!response.ok) {
alert("An error occured when attempting to fetch data.")
}
// a console.log statement here for the var 'response' results in "[object Promise]"
let parsedPromiseResonse = response.json();
let parsedResponse = await parsedPromiseResonse;
// printing out the 'parsedResponse' var gives me [object Object]
// printing out the 'parsedResponse[0]' var gives me undefined
EDIT:
For more context, the data to be retrieved in the URL is formatted like this:
{"variants":["some-string","some-string"]}
Any help would be greatly appreciated!

To access the json to have to call the entity variants then access to the items, something like
alert(parsedResponse.variants[0])
And the result should be
some-string

If you are referring to the varients array, then this is how you will get the array values.
parsedResponse["varients"]
For the first index
parsedResponse["varients"][0]

Related

why does my JSON file contain [object Object]?

I am using sqlite3 and nodeJS, and querying a database. I want to copy the queries into a json file. I run into problems with the json file having strings and objects. Why does my JSON file contain:
[object Object]
Here is my code:
db.all(sql, [], (err, rows) => {
if(err) {
throw err;
}rows.forEach((row) => {
arr_string = JSON.parse(JSON.stringify(row));
fs.writeFile("tempo.json", arr_string, function(err){
});
console.log(arr_string);
});
});
I would like to eventually use ajax requests for these entries.
arr_string = JSON.parse(JSON.stringify(row));
//^---------^--- This is parsing the string back to a new object.
You are parsing the stringified item to a new Object, hence the node.js file writer is trying to write the object to the write stream, resulting in interpreting it as [object Object].
Just omit the JSON.parse, so that the stream will effectively be a string instance:
arr_string = JSON.stringify(row);
Additionally, you should aggregate the result and write it only one time, or append to the file:
db.all(sql, [], (err, rows) => {
if(err) {
throw err;
}
let _strings = [];
const newline_separator = ''; // <-- use whatever separator you need.
rows.forEach((row) => {
arr_string = JSON.stringify(row);
console.log(arr_string);
_strings.push(arr_string);
});
fs.writeFile("tempo.json", _strings.join(newline_separator), function(err){});
});
Since it's a json, I would suggest you to provide us a more precise input, so that we can guess what the expected result is.
I think while storing JSON data into SQLite, you're not stringifying it. If you directly store JSON data into SQLite it'll store like [object Object] format. My suggestion is to stringify the data while storing in SQLite. And while retrieving only parse it. Then your problem will solve.
arr_string is actually not a string, as you JSON.parse d it. Remove the JSON.parse call.
The JSON.stringify() method converts a JavaScript value to a JSON string
arr_string = JSON.stringify(row);
"the problem now with doing that is now the JSON file only writes the last row (and i queried 4) and also I cannot call arr_string.caphi because its not an object anymore"
Create an empty array(list) and push each result of query in array.And then
finally convert it into JSON.
sample code :
var rows=[{"holla":"bolla"},{"holla":"bolla1"}];
console.log(JSON.stringify(rows));
JSON.stringify() takes JSON object and returns String
JSON.parse() takes String and returns JSON object
try :
rows.forEach((row) => {
arr_string = JSON.stringify(row); // 'row' data is converted to String
fs.writeFile("tempo.json", arr_string, function(err){
});`

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.

Accessing a javascript object

I have been working on this problem for quite a while now.
I am defining an array using the following:
let newJsonObject = {
"billing_name": document.getElementsByName("order[billing_name]")[0].value,
"email": document.getElementsByName("order[email]")[0].value,
};
I get the data from storage and keep it in a variable named parsedJson, then do the three following console.log operations:
console.log(parsedJson);
console.log(parsedJson.billing_name);
console.log(parsedJson["billing_name"]);
This first returns an object with the following:
parameters:
{"billing_name": "123", "email": "123"}
However, the following two things logged in the console are undefined.
I have also tried to create the object with the keys not having quotations, but I am still getting undefined
I don't understand why the log is returning null when the object is defined. Does anyone have any suggestions?
EDIT:
Here is how I am storing the data:
chrome.storage.sync.set({"parameters": JSON.stringify(newJsonObject)});
Here is how I am accessing it:
chrome.storage.sync.get("parameters", params => {
if(params === null){
//Nothing is even set, simply return
return;
}else{
//Actually data saved in params
let parsedJson = params;
console.log(parsedJson);
console.log(parsedJson.parameters.billing_name);
console.log(parsedJson["billing_name"]);
Here is a link to what is displayed in console
use JSON.parse converts your json string to object
try this
console.log(JSON.parse(parsedJson.parameters).billing_name);
Try this:
var test = JSON.parse(parsedJson.parameters);
console.log(test.billing_name);
this will work.

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.

alert a json response

I have the following json response I need to alert errors object through javascript.
{"sEcho":1,"iTotalRecords":1,"iTotalDisplayRecords":1,"aaData":{null},"errors":{"msisdn":"num\u00e9ro de t\u00e9l\u00e9phone non valide"}}
I m newbie with json and I couldn't find a way to alert my error rendered by my controller.
Many Thx
Try this:
// your json data
var s = '{"sEcho":1,"iTotalRecords":1,"iTotalDisplayRecords":1,"aaData":"{null}","errors":{"msisdn":"phone non valide"}}';
// change in json object
var obj = JSON.parse(s);
// get errors value
console.log(obj.errors);
Make sure that you have valid json data.
Try with below code
var j = '{"sEcho":1,"iTotalRecords":1,"iTotalDisplayRecords":1,"aaData":null,"errors":{"msisdn":"num\u00e9ro de t\u00e9l\u00e9phone non valide"}}';
var a = JSON.parse(j);
alert(a.errors.msisdn);
It will display message of msisdn property of errors, as msisdn is child property of errors.

Categories

Resources