converting string to JSON causing problems - json

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);
});

Related

JSON - Array Error for Multiline string output | nodejs | node-request

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));

Variable Assigning from Api to field - ReactJS , Javascript

For examplpe I am fetching the record through Json and in success function am storing the return data in localstorage to use
Output Json like
[{"1":"Core"},{"2":"Moderate"},{"3":"Remote"}]
It's returning as expected
but I can't populate the data in drop down, if i hard coded the same json it's working. Thanks in advance please help me to resolve.
$.ajax({
url: 'http://test.com',
//type: 'POST',
//data :Editorcontent,
success: function (data) {
let fieldes = JSON.parse(data)
localStorage.setItem('one',fieldes)
},
error: function () {
alert(url);
}
});
var selected = localStorage.getItem('one');
//selected = [{"1":"Core"},{"2":"Moderate"},{"3":"Remote"}]
//selected = selected.replace('\'',"'");
console.log(selected);
var editor = {
ajax: '',
ajaxFiles: '',
struct: {
buttons: ['top', 'bottom'] // buttons
},
fields: [
{
label: "Branch Name",
name: "DefaultBranchID",
values: selected,
type: 'select'
},
{
label: "Country:",
name: "CountryID",
type: 'multiselect',
attrs: [
{'pattern': '^[A-Za-z0-9_]+$'}
]
},
"selected" is the variable am assigning
OutPut for Branch Nam Drop down :-O/p

HUBOT Coffescript - JSON obejct

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

Get specific data from a JSON object (Steam Api)

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();
}

ExtJS 4 store and manage record

I have a question about extjs 4.
Below is my storeMsg
var storeMsg = this.getMessageStore();
storeMsg.load({
scope: this,
autoLoad: true,
params:{
read_conditions: Ext.JSON.encode({
"employee_rid": '7976',
"year" : '2013', //etos
"kind_holiday_rid" : '1',
"request_days" : '5'
})
},
callback: function(records, operation, success) {
// do something after the load finishes
console.log(records[0].get('remain'));
console.log(records[0].get('messages'));
}
});
and i take a json response like as
{"total":1,"success":true,"data":[{"status":"true","messages":"\u03a3\u03c9\u03c3\u03c4\u03cc \u03b1\u03af\u03c4\u03b7\u03bc\u03b1 \u03ac\u03b4\u03b5\u03b9\u03b1\u03c2","remain":"25"}]}
I want to take the field status from json (ex true) outside from storeMsg.load();
For example
var vstatus = Ext.StoreMgr.lookup(storeMsg).data.items[0].data.status
but i take message this vstatus is undefined
I have changed my variable (vstatus) of code :
var vstatus = Ext.StoreMgr.lookup(storeMsg).getProxy().getReader();
and I am taking and object like as
className "Ext.data.reader.Json"
and it has some attributes. An attribute is
jsonData
data
remain 25
status true
message "Is correct"
total 1
success true
and I give in
var vstatus = Ext.StoreMgr.lookup(storeMsg).getProxy().getReader().jsonData;
and I take this message (undefined).
Do you have any idea how take the value from jsonData.data.status = true;
tnx
and the fully code about store , proxy and reader is below
Ext.define('MHR.store.Message',{
extend : 'Ext.data.Store',
model : 'MHR.model.Message',
storeId : 'Message',
autoLoad : true,
proxy : {
type: 'ajax',
api: {
read : 'php/crud.php?action=check'
},
actionMethods: {
read : 'POST',
},
reader: {
type: 'json',
root: 'data',
rootProperty: 'data',
successProperty: 'success',
messageProperty: 'message'
},
extraParams : {
'read_conditions': ''
}
}
});
try with:
storeMsg.each(function(record) {
var status = record.get('status');
});