Wondering if anyone can help me with this - pretty much novice in scripting and not sure if I'm doing it right. I need to get an object from this JSON string and it keeps giving me "undefined" error.
Here's the JSON:
`
{ data:
[ { type: 'gif',
id: 'Cmr1OMJ2FN0B2',
slug: 'hello-Cmr1OMJ2FN0B2',
url: 'https://giphy.com/gifs/hello-Cmr1OMJ2FN0B2',
bitly_gif_url: 'https://gph.is/2bZufS7',
bitly_url: 'https://gph.is/2bZufS7',
embed_url: 'https://giphy.com/embed/Cmr1OMJ2FN0B2',
username: '',
source: 'https://www.fanpop.com/clubs/penguins-of-madagascar/images/37800672/title/hello-photo',
rating: 'g',
content_url: '',
source_tld: 'www.fanpop.com',
source_post_url: 'https://www.fanpop.com/clubs/penguins-of-madagascar/images/37800672/title/hello-photo',
is_indexable: 0,
import_datetime: '2016-09-05 13:48:36',
trending_datetime: '2017-09-19 14:26:18',
images: [Object],
title: 'bom dia hello GIF' } ],
pagination: { total_count: 2516, count: 1, offset: 0 },
meta:
{ status: 200,
msg: 'OK',
response_id: '5a28576867382f644dc7d33b' } }
`
And here's my HUBOT script:
`
robot.hear /^(no)$|^.*(\sno\s).*$/i, (res) ->
api_url = 'https://api.giphy.com'
path = '/v1/gifs/search'
url = "#{api_url}#{path}"
robot.http(url)
.query
q: "nono+penguin"
rating: 'g'
limit: 1
fmt: 'json'
.header('api_key', giphyAuthToken)
.header('Content-Type', 'application/json')
.get() (err, res, body) ->
# error checking code here
if err
console.log err
else
data = JSON.parse(body)
console.log data #this prints above data
console.log "success....got giphy response"
console.log data.images.original.url #This is giving error that original is undefined
process.exit(1)
`
Wondering how can I access this "images" object from Giphy's response.
Thanks
The data field in your object is an Array so you need to put the index in order to access the content, i.e.
data = JSON.parse(body)
console.log data[0].images
Related
I have the Json response from an api in the below format
[
{
id: 1,
class: '10',
section: 'A',
subject: 'Social'
},
{
id: 2,
class: '8',
section: 'C',
subject: 'Social'
},
{
id: 3,
class: '9',
section: 'A',
subject: 'Social'
}
]
I am storing the json response in a state variable and able to print the above json array successfully.
async ListAllTodaysClasses() {
try {
let data = new FormData();
data.append('id', this.state.id)
data.append('year',this.state.year)
data.append('month',this.state.month)
data.append('day', this.state.day)
var url = this.state.url;
console.log(url);
let response = await fetch(url, {
method: 'POST',
body: data
});
let res = await response.json();
this.setState({
subjects: res
})
console.log(this.state.subjects)
} catch(error) {
this.setState({error: error});
console.log("error " + error);
}
}
Here I am trying to loop over an json response array.
this.state.subjects.map((item, key) => (
<TouchableOpacity key={key}>
<View>
{
<Text style={styles.textColor2}>{item.class}th-{item.section}/ {item.subject}</Text>
}
</View>
</TouchableOpacity>
))
But I am getting Typeerror: undefined is not a function
Your question has nothing to do with JSON. You're storing the result of calling response.json(), which parses the JSON in the response and returns the parsed result.
Your code to store it is correct:
this.setState({
subjects: res
})
so I suspect the problem is in your constructor where you set your initial state. The correct initial state for subjects would be like this:
// In your constructor
this.state = {
/*...any other state you have...*/,
subjects: []
};
Notice that subjects is an empty array. I suspect you're setting it to {} (an empty object) or "" (an empty string) or similar. (You're clearly not failing to initialize it, and not using null, since that would produce a different error.)
Side note: Although your setState call is correct, what follows it is not:
this.setState({
subjects: res
})
console.log(this.state.subjects) // <=== Will not see the updated state
Remember that state updates are asynchronous.
You probably need to init your state.subjects:
class YourClassName extends React.Component {
constructor() {
this.state = {
subjects: []
}
}
}
I ran the following code in node js
const request = require("request");
const GetUserInventory = {
method: 'GET',
url: 'https://api-trade.opskins.com/ITrade/GetUserInventory/v1/',
qs: { uid: '3192035', app_id: '1' },
json: true
};
request(GetUserInventory, function (error, response, body) {
if (error) throw new Error(error);
console.log(body);
});
The output I got is the following. Here the values of the strings are not displayed. That is, they are displayed as [object] How do I get the desired output as stated in the picture?
{
status: 1,
time: 1536729167,
current_page: 1,
total_pages: 1,
response: {
items: [
[Object]
],
total: '1',
items_in_active_offers: null,
user_data: {
username: 'Mowrish gamdom.com',
avatar: 'https://steamcdn-a.opskins.media/steamcommunity/public/images/avatars/d7/d7cf2c088d4398bed904ae540b36211e1af202f2.jpg'
},
sort_parameters: [
[Object],
[Object],
[Object],
[Object],
[Object],
[Object]
]
}
}
The output, that I expect is as follows. How to get this output?
I have tried JSON.parse of body before console.log() instead of json: true value in GetUserInventory. It didn't work. And Also, I tried JSON.stringify of body. The same happened with it too
Try following if you want the output same as in screenshot you posted
request(GetUserInventory, function (error, response, body) {
if (error) throw new Error(error);
obj = JSON.stringify(body);
console.log(obj);
});
you have issue with response body. so there may be you have not set content-type when you call API.
The header just denotes what the content is encoded in. It is not necessarily possible to deduce the type of the content from the content itself, i.e. you can't necessarily just look at the content and know what to do with it. That's what HTTP headers are for, they tell the recipient what kind of content they're (supposedly) dealing with.
pass content type in header:
Content-type: application/json; charset=utf-8;
so your response will be in JSON format you can access it.
or you can try this, this will also works.
obj = JSON.parse(JSON.stringify(body));
I've been working on this issue for some time now, and I can't seem to figure out what exactly the issue is. In Dart(2) the json.encode() does not seem to be giving me the result I am aiming for.
I am passing in a Map<String, dynamic> that looks like this:
_data = <String, dynamic>{
'uid': newProfileCreationModel.accountID,
'displayName': newProfileCreationModel.profileName,
'greeting': newProfileCreationModel.profileBody ?? '',
'avatarSrc': newProfileCreationModel.avatarSrc,
'heroSrc': newProfileCreationModel.heroSrc,
'accountType': newProfileCreationModel.accountType,
'cityID': newProfileCreationModel.cityID,
'cityName': newProfileCreationModel.cityName,
'country': newProfileCreationModel.countryCode,
'state': newProfileCreationModel.stateAbv,
};
and using this to convert it to JSON
final String _jsonData = json.encode(_data);
Then I am sending it to a google cloud function in the following way.
final Uri _uri = Uri.parse(functionUrl);
final String _jsonData = json.encode(_data);
final String _userToken = await AuthenticationService.getUserToken();
HttpClient client = new HttpClient();
HttpClientRequest request = await client.postUrl(_uri);
request.headers.set('Authorization', 'Bearer ' + _userToken);
request.headers.set('Content-Type', 'application/json; charset=utf-8');
print('Encoded: ' + _jsonData);
request.write(_jsonData);
HttpClientResponse response = await request.close();
if(response.statusCode != HttpStatus.OK){ ...
The line where I print the encoded string outputs this to the console:
05-04 18:52:57.902 26146-26200/com.app.name I/flutter: Encoded: {"uid":'123456789',"displayName":"James","greeting":"My Greetings!","avatarSrc":"http://cdn.free.com/someImage.jpg","heroSrc":"http://cdn.free.com/someImage.jpg","accountType":"per","cityID":1,"cityName":"Eugene","country":"US","state":"OR"}
However the request.write(_jsonData) fails with the following firebase console log error Request Body Missing Data the response that looks like this in the
Firebase Console Log.
Request body is missing data. {
uid: '123456789',
displayName: 'James',
greeting: 'My Greetings!',
avatarSrc: 'http://cdn.free.com/someImage.jpg',
heroSrc: 'http://cdn.free.com/someImage.jpg', accountType: 'per',
cityID: 1,
cityName: 'Eugene',
country: 'US',
state: 'OR'
}
Invalid request IncomingMessage {
_readableState:
ReadableState {
objectMode: false,
highWaterMark: 16384,
buffer: BufferList { head: null, tail: null, length: 0 },
length: 0,
pipes: null,
pipesCount: 0,
flowing: true,
ended: true,
endEmitted: true,
reading: false,
sync: false,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: false,
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
socket:
Socket {
connecting: false,
_hadError: false,
_handle:
TCP {
bytesRead: 13285,
_externalStream: {},
fd: 14,
reading: true,
owner: [Circular],
onread: [Function: onread],
onconnection: null,
writeQueueSize: 0,
_consumed: true },
_parent: null,
_host: null,
The interesting part is that the data is getting through as is clearly displayed in the firebase console log, however it won't recognize it as the body.
Raw Data Approach
When I try sending a raw JSON object through the request.write() as
request.write({'hello':'universe'});
I get a totally different kind of error in the firebase console.
SyntaxError: Unexpected token h in JSON at position 1
at Object.parse (native)
at parse (/var/tmp/worker/node_modules/body-parser/lib/types/json.js:84:17)
at /var/tmp/worker/node_modules/body-parser/lib/read.js:102:18
at IncomingMessage.onEnd (/var/tmp/worker/node_modules/raw-body/index.js:149:7)
at IncomingMessage.g (events.js:292:16)
at emitNone (events.js:86:13)
at IncomingMessage.emit (events.js:185:7)
at endReadableNT (_stream_readable.js:974:12)
at _combinedTickCallback (internal/process/next_tick.js:80:11)
at process._tickDomainCallback (internal/process/next_tick.js:128:9)
on the firebase side I am using a function using a callable, this is where the firebase console logs are being recorded from
export const finalizeProfile = functions.https.onCall((data, context) => {
//CODE
});
Is anyone able to spot what I may be doing incorrectly?
The solution was hidden in plain sight. The issue had to do with a missing field. for Firebase Cloud Functions, the contents 'body', as referred to in the error message body is missing data, literally means it requires a key named data which contains the object of data you are passing.
The google docs are not(ish) crystal clear on this, as they are missing an example https://firebase.google.com/docs/functions/callable-reference#request_body
This is how the data must be sent to functions.https.onCall(), note the Data Field as compared to the original question which did not include this:
{
"data":{
"uid":"123456789",
"displayName":"James",
"greeting":"My Greeting!",
"avatarSrc":"http://cdn.free.com/someImage.jpg",
"heroSrc":"http://cdn.free.com/someImage.jpg",
"accountType":"per",
"cityID":1,
"cityName":"Eugene",
"country":"OR",
"state":"AL"
}
}
The resulting code that now works looks as follows:
// Helper function to format any map to be used for Firebase
Map prepMapForFirebaseJSON(Map<String, dynamic> mapData){
Map<String, Map<String, dynamic>> _fireJson = {
'data' : mapData
};
return _fireJson;
}
// Process HTTP request
final Uri _uri = Uri.parse(functionUrl);
final String _jsonData = json.encode(prepMapForFirebaseJSON(mapData));
final String _userToken = await AuthenticationService.getUserToken();
HttpClient client = new HttpClient();
HttpClientRequest request = await client.postUrl(_uri);
request.headers.set('Authorization', 'Bearer ' + _userToken);
request.headers.set('Content-Type', 'application/json; charset=utf-8');
request.write(_jsonData);
request.close();
I think closing the request is missing:
request.write(_jsonData);
var response = await request.close();
So I am practising some nodejs and this time I am playing around with steam api and json objects. But I am having some problems.
So, from the Steam api,
http://steamcommunity.com/profiles/<steamid>/inventory/json/730/2
I got the json from this code,
var request = require('request');
var url = "http://steamcommunity.com/profiles/<steamid>/inventory/json/730/2"
request({
url: url,
json: true
}, function (error, response, body) {
if (!error && response.statusCode === 200) {
var json = JSON.parse(body);
console.log(body)
}
});
And the json looks lite this, json-link
From the json I want to take out the classid and instanceid from each of the items, but there comes the problem. I don't know how. I know I need to parse it but nothing more unfortunately.
Would be very helpful if someone could explain how, or link a guide/tutorial so I can learn.
Thanks!
EDIT:
var request = require('request');
var _ = require('lodash');
var url = "http://steamcommunity.com/profiles/76561198007691048/inventory/json/730/2";
request({
url: url,
json: true
}, function jsonParse(error, response, data) {
console.log(data.rgDescriptions);
var item = getItems(data.rgDescriptions);
console.log(item);
}
);
function getItems(data){
var item = data;
if(!item){
return "error";
}
return _(item).keys().map(function(id){
return _.pick([id], "name");}).value();
Console give me this; [ {}, {}, {}, {}, {}, {}, {}, {},
{},.... ]
JSON look like this;
'1293508920_0':
{ appid: '730',
classid: '1293508920',
instanceid: '0',
icon_url: '-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXU5A1PIYQNqhpOSV-fRPasw8rsUFJ5KBFZv668FF4u1qubIW4Su4mzxYHbzqGtZ-KGlz8EuJcg3rnE9NiijVe3_UY-Zzr2JJjVLFEEeiQRtg',
icon_drag_url: '',
name: 'Shadow Case',
market_hash_name: 'Shadow Case',
market_name: 'Shadow Case',
name_color: 'D2D2D2',
background_color: '',
type: 'Base Grade Container',
tradable: 1,
marketable: 1,
commodity: 1,
market_tradable_restriction: '7',
},
'1644880589_236997301':
{ appid: '730',
classid: '1644880589',
instanceid: '236997301',
icon_url: '-9a81dlWLwJ2UUGcVs_nsVtzdOEdtWwKGZZLQHTxDZ7I56KU0Zwwo4NUX4oFJZEHLbXU5A1PIYQNqhpOSV-fRPasw8rsUFJ4MAlVo6n3e1Y27OPafjBN09izq42ChfbzNvXTlGkD6p0lj7_FpNjx0VDj_UBoZ272cNfBdg48MAyB-VS3xum61Me_ot2XnqkB5QYc',
icon_drag_url: '',
name: 'MLG Columbus 2016 Mirage Souvenir Package',
market_hash_name: 'MLG Columbus 2016 Mirage Souvenir Package',
market_name: 'MLG Columbus 2016 Mirage Souvenir Package',
name_color: 'D2D2D2',
background_color: '',
type: 'Base Grade Container',
tradable: 1,
marketable: 1,
commodity: 0,
market_tradable_restriction: '7',
},
To work with complex objects or collections you can use lodash library.
So, you have json with the following format:
{
"success":true,
"rgInventory": {
"5719625206": {"id":"5719625206","classid":"1651313004","instanceid":"188530139","amount":"1","pos":1},
"5719034454": {"id":"5719034454","classid":"1649582636","instanceid":"188530139","amount":"1","pos":2},
"5718628709": {"id":"5718628709","classid":"1649582636","instanceid":"188530139","amount":"1","pos":3},
...
}
}
To extract array of required items, first of all install lodash library in your project: npm i -S, after that add this code into your file:
var _ = require('lodash');
function extractItems(data) {
var rgInventory = _.get(data, 'rgInventory');
if (!rgInventory) {
return [];
}
return _(rgInventory)
.keys()
.map(function(id) {
return _.pick(rgInventory[id], ['classid', 'instanceid']);
})
.value();
}
I'm requesting data from an api that isn't configured properly.
It serves as text/html, but when I run JSON.parse(data) I get an parse error. and I do data.trade it says undefined.
If I just echo the data it looks like this (sample, not the full object):
"{\"buyOrder\":[{\"price\":\"5080.000000\"}]}"
Here is the url in question:
http://www.btc38.com/trade/getTradeList.php?coinname=BTC
I'm using request module to fetch the data.
How would I convert this string into a JSON object?
Here is the request:
var url = 'http://www.btc38.com/trade/getTradeList.php?coinname=BTC'
, json = true;
request.get({ url: url, json: json, strictSSL: false, headers: { 'User-Agent' : 'request x.y' } }, function (err, resp, data) {
c.log(data.trade); //undefined
});
Trimming the string got everything working well for me:
var request = require('request');
options = {
url: 'http://www.btc38.com/trade/getTradeList.php?coinname=BTC',
headers: {
'User-Agent': 'request x.y'
}
};
request(options, function(error, response, body) {
var cleaned = body.trim();
var json = JSON.parse(cleaned);
console.log(json.trade);
});
Output (truncated):
[ { price: '5069.000000',
volume: '0.494900',
time: '2013-12-15 16:05:44',
type: '2' },
{ price: '5069.000000',
volume: '0.230497',
time: '2013-12-15 16:02:37',
type: '2' },
{ price: '5100.000000',
volume: '0.058963',
time: '2013-12-15 15:58:27',
type: '1' },
{ price: '5100.000000',
volume: '0.099900',
time: '2013-12-15 15:58:27',
type: '1' },
{ price: '5099.000000',
volume: '0.344058',
time: '2013-12-15 15:56:58',
type: '1' },
{ price: '5069.000000',
volume: '0.027464',
time: '2013-12-15 15:55:35',
type: '2' } ... ]
Without seeing more of your code I won't be able to tell what's wrong, but I would suggest you use the request-json (npm install request-json) package for something like this.
I just ran the following in Node and got a response:
var request = require('request-json');
var client = request.newClient('http://www.btc38.com');
client.get('/trade/getTradeList.php?coinname=BTC', function(err,res,body) {
// body is a JSON object
return console.log(body);
});