Unable to parse JSON - json

I am making a request to an external API from my node server:
request("https://api.data.gov/ed/collegescorecard/v1/schools/?id=168421&api_key=", function(error, response, body) {
console.log(JSON.parse(body));
console.log(body.metadata);
console.log(JSON.parse(body.metadata));
});
The first console gives the output:
{ metadata: { total: 1, page: 0, per_page: 20 },
results:
[ { '1996': [Object],
'1997': [Object],
'1998': [Object],
'1999': [Object],
'2000': [Object],
'2001': [Object],
'2002': [Object],
'2003': [Object],
'2004': [Object],
'2005': [Object],
'2006': [Object],
'2007': [Object],
'2008': [Object],
'2009': [Object],
'2010': [Object],
'2011': [Object],
'2012': [Object],
'2013': [Object],
'2014': [Object],
ope6_id: 2233,
location: [Object],
id: 168421,
school: [Object],
ope8_id: 223300 } ] }
The second log gives me an 'undefined'
The third log gives me SyntaxError: Unexpected token u
Why? How do I access only the metadata or results field?

you are trying to use body when this is not the json object. You have used JSON.parse only to console log, but haven't stored the value
var jsonBody = JSON.parse(body)
console.log(jsonBody);
console.log(jsonBody.metadata);
alternatively you could have done this console.log(JSON.parse(body).metadata);. You are parsing body as a json and then getting metadata from that parsed json

Related

Validate ABI JSon (Ethereum)

i've a problem with the following Json :
[ { constant: false,
inputs: [Object],
name: 'set',
outputs: [],
type: 'function'
}, {
constant: true,
inputs: [],
name: 'get',
outputs: [Object],
type: 'function'
}, {
anonymous: false,
inputs: [Object],
name: 'ItBlinks',
type: 'event'
},
set: {
[Function: bound]
request: [Function: bound],
call: [Function: bound],
sendTransaction: [Function: bound],
estimateGas: [Function: bound],
getData: [Function: bound],
uint256: [Circular]
},
get: {
[Function: bound]
request: [Function: bound],
call: [Function: bound],
sendTransaction: [Function: bound],
estimateGas: [Function: bound],
getData: [Function: bound],
'': [Circular]
},
allEvents: [Function: bound],
ItBlinks: {
[Function: bound] uint256: [Function: bound]
}
}
This JSon is the ABI and this should be add to my contract into my wallet (Ethereum Wallet) to send information (in this case, made a blink event on my raspberry PI)
When I add these line into my contract in my ethereum wallet, it tell me my Json is not correct.
I've try to validate, but it give me an error, and i cannot solve it. (I'm a beginner in JSon)
Somebody can help me to validate the get / set method? to be a valid JSon format?
This is the full return with coinbase (the address and coinbase is modified) :
coinbase : 0x20408a19c567a475545947600a95130f24f7C123
{ _eth:
Eth {
_requestManager: { provider: [Object], polls: {}, timeout: null },
getBalance: { [Function] request: [Function: bound ], call: 'eth_getBalance' },
getStorageAt: { [Function] request: [Function: bound ], call: 'eth_getStorageAt' },
getCode: { [Function] request: [Function: bound ], call: 'eth_getCode' },
getBlock: { [Function] request: [Function: bound ], call: [Function] },
getUncle: { [Function] request: [Function: bound ], call: [Function] },
getCompilers: { [Function] request: [Function: bound ], call: 'eth_getCompilers' },
getBlockTransactionCount: { [Function] request: [Function: bound ], call: [Function] },
getBlockUncleCount: { [Function] request: [Function: bound ], call: [Function] },
getTransaction:
{ [Function]
request: [Function: bound ],
call: 'eth_getTransactionByHash' },
getTransactionFromBlock: { [Function] request: [Function: bound ], call: [Function] },
getTransactionReceipt:
{ [Function]
request: [Function: bound ],
call: 'eth_getTransactionReceipt' },
getTransactionCount: { [Function] request: [Function: bound ], call: 'eth_getTransactionCount' },
call: { [Function] request: [Function: bound ], call: 'eth_call' },
estimateGas: { [Function] request: [Function: bound ], call: 'eth_estimateGas' },
sendRawTransaction: { [Function] request: [Function: bound ], call: 'eth_sendRawTransaction' },
signTransaction: { [Function] request: [Function: bound ], call: 'eth_signTransaction' },
sendTransaction: { [Function] request: [Function: bound ], call: 'eth_sendTransaction' },
sign: { [Function] request: [Function: bound ], call: 'eth_sign' },
compile: { solidity: [Object], lll: [Object], serpent: [Object] },
submitWork: { [Function] request: [Function: bound ], call: 'eth_submitWork' },
getWork: { [Function] request: [Function: bound ], call: 'eth_getWork' },
coinbase: [Getter],
getCoinbase: { [Function] request: [Function: bound ] },
mining: [Getter],
getMining: { [Function] request: [Function: bound ] },
hashrate: [Getter],
getHashrate: { [Function] request: [Function: bound ] },
syncing: [Getter],
getSyncing: { [Function] request: [Function: bound ] },
gasPrice: [Getter],
getGasPrice: { [Function] request: [Function: bound ] },
accounts: [Getter],
getAccounts: { [Function] request: [Function: bound ] },
blockNumber: [Getter],
getBlockNumber: { [Function] request: [Function: bound ] },
protocolVersion: [Getter],
getProtocolVersion: { [Function] request: [Function: bound ] },
iban:
{ [Function]
fromAddress: [Function],
fromBban: [Function],
createIndirect: [Function],
isValid: [Function] },
sendIBANTransaction: [Function: bound ] },
transactionHash: null,
address: '0x9535eb707582edb3317dfdcdb365ce4186500C123',
abi:
[ { constant: false,
inputs: [Object],
name: 'set',
outputs: [],
type: 'function' },
{ constant: true,
inputs: [],
name: 'get',
outputs: [Object],
type: 'function' },
{ anonymous: false,
inputs: [Object],
name: 'ItBlinks',
type: 'event' } ],
set:
{ [Function: bound ]
request: [Function: bound ],
call: [Function: bound ],
sendTransaction: [Function: bound ],
estimateGas: [Function: bound ],
getData: [Function: bound ],
uint256: [Circular] },
get:
{ [Function: bound ]
request: [Function: bound ],
call: [Function: bound ],
sendTransaction: [Function: bound ],
estimateGas: [Function: bound ],
getData: [Function: bound ],
'': [Circular] },
allEvents: [Function: bound ],
ItBlinks: { [Function: bound ] uint256: [Function: bound ] }
}
You do not have valid JSON. JSON has key/value pairs with keys being strings delimited by double quotes. Details of JSON can be found here
From the Ethereum documentation this is an example of JSON in the ABI:
[{
"type":"event",
"inputs": [{"name":"a","type":"uint256","indexed":true},
{"name":"b","type":"bytes32","indexed":false}],
"name":"Event"
}, {
"type":"event",
"inputs": [{"name":"a","type":"uint256","indexed":true},
{"name":"b","type":"bytes32","indexed":false}],
"name":"Event2"
}, {
"type":"event",
"inputs": [{"name":"a","type":"uint256","indexed":true},
{"name":"b","type":"bytes32","indexed":false}],
"name":"Event2"
}, {
"type":"function",
"inputs": [{"name":"a","type":"uint256"}],
"name":"foo",
"outputs": []
}]
Details of the ethereum contract ABI can be found here
What you were showing is a payload from coinbase it contains lots of information regarding your request, the smart-contracts ABI is one of them.
In reality it is only
abi:[ { constant: false,
inputs: [Object],
name: 'set',
outputs: [],
type: 'function' },
{ constant: true,
inputs: [],
name: 'get',
outputs: [Object],
type: 'function' },
{ anonymous: false,
inputs: [Object],
name: 'ItBlinks',
type: 'event' } ]
you can access the abi by doing this
coinbase[0x20408a19c567a475545947600a95130f24f7C123].abi
i don't know your exact use case but i suggest you read about smart contracts abis here
I did have the same issue.
The problem is this [Object] inside your JSON
You probably get the ABI from console.log object.
You have to convert this JSON object to a string, and then console.log it and grab the output which will be a valid JSON.

Doing a proper MongoDB Query (TypeError: Converting circular structure to JSON)

I am querying something that I have done multiple times. Take a look, I can't seem to understand.
/* GET all things */
app.get('/things', function(req, res) {
var search = req.query.search;
console.log(search); //works properly and prints strings
Thing.find({ name: {$regex : search}}, function(err, val) {
if(err) throw error;
console.log(val); // returns some horrible JSON
res.send(JSON.stringify(val)); // Throws TypeError
});
})
I thought maybe my query was wrong and that perhaps maybe it's the Mongo shell throwing issues, but when I went into the Mongo shell.
use dbname
> db.booking.find({name: {$regex: "G"}})
>{ "_id" : ObjectId("58238283565e2c1940b16d48"), "name" : "Go to Lesters"}
This is what happens when I print val.
Readable {
pool: null,
server: null,
disconnectHandler:
{ s: { storedOps: [], storeOptions: [Object], topology: [Object] },
length: [Getter] },
bson: {},
ns: 'vectio.booking',
cmd:
{ find: 'vectio.booking',
limit: 0,
skip: 0,
query: { name: [Object] },
slaveOk: true,
readPreference: { preference: 'primary', tags: undefined, options: [Object] } },
options:
{ skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
readPreference: { preference: 'primary', tags: undefined, options: [Object] },
db:
EventEmitter {
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s: [Object],
serverConfig: [Getter],
bufferMaxEntries: [Getter],
databaseName: [Getter] },
promiseLibrary: [Function: Promise],
disconnectHandler: { s: [Object], length: [Getter] } },
topology:
EventEmitter {
domain: null,
_events:
{ reconnect: [Function],
reconnectFailed: [Function],
timeout: [Object],
error: [Object],
close: [Function],
destroy: [Object],
serverDescriptionChanged: [Function],
serverHeartbeatStarted: [Function],
serverHeartbeatSucceeded: [Function],
serverHeartbeatFailed: [Function],
serverOpening: [Function],
serverClosed: [Function],
topologyOpening: [Function],
topologyClosed: [Function],
topologyDescriptionChanged: [Function],
attemptReconnect: [Function],
monitoring: [Function] },
_eventsCount: 17,
_maxListeners: undefined,
id: 0,
s:
{ options: [Object],
logger: [Object],
Cursor: [Object],
bson: {},
pool: [Object],
disconnectHandler: [Object],
monitoring: true,
inTopology: false,
monitoringInterval: 5000,
topologyId: -1 },
ismaster:
{ ismaster: true,
maxBsonObjectSize: 16777216,
maxMessageSizeBytes: 48000000,
maxWriteBatchSize: 1000,
localTime: 2016-11-09T20:41:56.152Z,
maxWireVersion: 2,
minWireVersion: 0,
ok: 1 },
lastIsMasterMS: 6,
monitoringProcessId:
Timeout {
_called: false,
_idleTimeout: 5000,
_idlePrev: [Object],
_idleNext: [Object],
_idleStart: 255,
_onTimeout: [Function],
_repeat: null },
initalConnect: false,
wireProtocolHandler: {},
_type: 'server',
clientInfo:
{ driver: [Object],
os: [Object],
platform: 'Node.js v6.2.1, LE, mongodb-core: 2.0.13' },
lastUpdateTime: 0,
lastWriteDate: 0,
staleness: 0 },
cursorState:
{ cursorId: null,
cmd:
{ find: 'vectio.booking',
limit: 0,
skip: 0,
query: [Object],
slaveOk: true,
readPreference: [Object] },
documents: [],
cursorIndex: 0,
dead: false,
killed: false,
init: false,
notified: false,
limit: 0,
skip: 0,
batchSize: 1000,
currentLimit: 0,
transforms: undefined },
logger: { className: 'Cursor' },
_readableState:
ReadableState {
objectMode: true,
highWaterMark: 16,
buffer: [],
length: 0,
pipes: null,
pipesCount: 0,
flowing: null,
ended: false,
endEmitted: false,
reading: false,
sync: true,
needReadable: false,
emittedReadable: false,
readableListening: false,
resumeScheduled: false,
defaultEncoding: 'utf8',
ranOut: false,
awaitDrain: 0,
readingMore: false,
decoder: null,
encoding: null },
readable: true,
domain: null,
_events: {},
_eventsCount: 0,
_maxListeners: undefined,
s:
{ numberOfRetries: 5,
tailableRetryInterval: 500,
currentNumberOfRetries: 5,
state: 0,
streamOptions: {},
bson: {},
ns: 'vectio.booking',
cmd:
{ find: 'vectio.booking',
limit: 0,
skip: 0,
query: [Object],
slaveOk: true,
readPreference: [Object] },
options:
{ skip: 0,
limit: 0,
raw: undefined,
hint: null,
timeout: undefined,
slaveOk: true,
readPreference: [Object],
db: [Object],
promiseLibrary: [Function: Promise],
disconnectHandler: [Object] },
topology:
EventEmitter {
domain: null,
_events: [Object],
_eventsCount: 17,
_maxListeners: undefined,
id: 0,
s: [Object],
ismaster: [Object],
lastIsMasterMS: 6,
monitoringProcessId: [Object],
initalConnect: false,
wireProtocolHandler: {},
_type: 'server',
clientInfo: [Object],
lastUpdateTime: 0,
lastWriteDate: 0,
staleness: 0 },
topologyOptions:
{ host: 'localhost',
port: 27017,
disconnectHandler: [Object],
cursorFactory: [Object],
reconnect: true,
emitError: true,
size: 5,
socketOptions: {},
clientInfo: [Object],
readPreference: [Object],
promiseLibrary: [Function: Promise],
bson: {} },
promiseLibrary: [Function: Promise],
currentDoc: null },
sortValue: undefined }
/home/dilraj/Documents/Vectio/scenario-dilraj/node_modules/mongodb/lib/utils.js:99
process.nextTick(function() { throw err; });
^
TypeError: Converting circular structure to JSON
I am trying to get something like
{
_id: ObjectId("58238283565e2c1940b16d48"),
name: "Go to Lesters"
}
or something similar, as long as it makes sense! I just haven't seen anything like this.
I am using Node's Express JS framework, and the only modules I have are Nodemon, Express, bodyParser and Mongo. Nothing else! Thank you, appreciate the love!
The object you are logging is the Mongo cursor. This can be useful at times but to just get the document that is not what you need.
Thing.find(query).toArray(function(err, result){ ... })
Should just return the documents that match your query.
If you request returns a single object, you can also use
Thing.findOne({ name: {$regex : search}}, function(err, val) {
You can use the same syntax but you need to handle the promise using .then
or use async await

MongoDB, find() result, convert to json

email: {"email":"aaa#bbb.eu"}
{ _mongooseOptions: {},
mongooseCollection:
{ collection:
{ db: [Object],
collectionName: 'parties',
internalHint: null,
opts: {},
slaveOk: false,
serializeFunctions: false,
raw: false,
pkFactory: [Object],
serverCapabilities: undefined },
opts: { bufferCommands: true, capped: false },
name: 'parties',
conn:
{ base: [Object],
collections: [Object],
models: [Object],
replica: false,
hosts: null,
host: 'localhost',
port: 27017,
user: undefined,
pass: undefined,
name: 'pluserDB',
options: [Object],
otherDbs: [],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
_listening: true,
_events: {},
db: [Object] },
queue: [],
buffer: false },
model:
{ [Function: model]
base:
{ connections: [Object],
plugins: [],
models: [Object],
modelSchemas: [Object],
options: [Object] },
modelName: 'Party',
model: [Function: model],
db:
{ base: [Object],
collections: [Object],
models: [Object],
replica: false,
hosts: null,
host: 'localhost',
port: 27017,
user: undefined,
pass: undefined,
name: 'pluserDB',
options: [Object],
otherDbs: [],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
_listening: true,
_events: {},
db: [Object] },
discriminators: undefined,
schema:
{ paths: [Object],
subpaths: {},
virtuals: [Object],
nested: {},
inherits: {},
callQueue: [],
_indexes: [],
methods: {},
statics: {},
tree: [Object],
_requiredpaths: undefined,
discriminatorMapping: undefined,
_indexedpaths: undefined,
options: [Object],
_events: {} },
options: undefined,
collection:
{ collection: [Object],
opts: [Object],
name: 'parties',
conn: [Object],
queue: [],
buffer: false } },
op: 'find',
options: {},
_conditions: { email: '{"email":"aaa#bbb.eu"}' },
_fields: { email: 1, _id: 0 },
_update: undefined,
_path: undefined,
_distinct: undefined,
_collection:
{ collection:
{ collection: [Object],
opts: [Object],
name: 'parties',
conn: [Object],
queue: [],
buffer: false },
collectionName: undefined },
_traceFunction: undefined,
_castError: null }
Please have a look at code below:
var parties = Party.find({ email: email }, { email: 1, _id: 0 });
this query returns 3 documents.
Now I want to send result and stringify these documents:
response.json(parties);
I get error here because parties contains circular references and does not just contain plain data I need here.
Question is:
How can I stringify result of find() method here?
I know what my mistake was.
MongoDB and it's shell is not the same as Mongoose API.
find() method needs different arguments for both.
The one I needed here is:
Party.find({ 'email': email }, 'email', function (err, parties) { response.json(parties)});

parse a values from json data

Am trying to get values from a json data using node.js
Following is the json data(It is dynamic), it may contains names like tcp,ipp,http,udp,https .here i only displaying tcp and ipp only
sample json
[ { '$':
{ name: 'tcp',
showname: 'tnternet crinting Protocol',
size: '584',
pos: '202' },
field: [ [Object], [Object], [Object], [Object] ] },
{ '$':
{ name: 'ipp',
showname: 'Internet Printing Protocol',
size: '584',
pos: '202' },
field: [ [Object], [Object], [Object], [Object], [Object], [Object] ] } ]
i need to get the details of ipp only .
(any other methods without using sample[1] ,like name =ipp from the json data)
example
{ '$':
{ name: 'ipp',
showname: 'Internet Printing Protocol',
size: '584',
pos: '202' },
field:
[ { '$': [Object] },
{ '$': [Object] },
{ '$': [Object] },
{ '$': [Object], field: [Object] },
{ '$': [Object], field: [Object] },
{ '$': [Object] } ] }
You could do it using lodash as follows:
var result = _.result(_.find(list, { '$': {'name':'ipp'} }), '$');
Plunker:
http://plnkr.co/edit/unh9wZuDCnIETE7EWHmD?p=preview
Lodash:
https://lodash.com/docs#find
You'd have to iterate, and look for the name
var ipp = null;
sample.forEach(function(o) {
if ( o['$'].name === 'ipp' ) {
ipp = o;
return false;
}
});
// ipp === object here
FIDDLE

AWS requests using nodeJS

I have a webpage which has a button. On clicking of button it calls a nodejs method which returns the status of my EC2 instances on my AWS account. To host webpage I have used nodeJS. For connection between my aws account and webpage I have used AWS NodeJS sdk.
The response I am getting (statuses of EC2) is in json format.Following is the response-
{ InstanceStatuses:
[ { InstanceId: 'i-67441a9c',
AvailabilityZone: 'us-east-1c',
Events: [],
InstanceState: [Object],
SystemStatus: [Object],
InstanceStatus: [Object] },
{ InstanceId: 'i-feac4e0f',
AvailabilityZone: 'us-east-1b',
Events: [],
InstanceState: [Object],
SystemStatus: [Object],
InstanceStatus: [Object] } ] }
C:\NodeTest>node DescribeInstances.js
{ InstanceStatuses:
[ { InstanceId: 'i-67441a9c',
AvailabilityZone: 'us-east-1c',
Events: [],
InstanceState: [Object],
SystemStatus: [Object],
InstanceStatus: [Object] },
{ InstanceId: 'i-feac4e0f',
AvailabilityZone: 'us-east-1b',
Events: [],
InstanceState: [Object],
SystemStatus: [Object],
InstanceStatus: [Object] } ] }
This response is coming in command prompt. Now I want this response to be displayed on a webpage. How should I do it. Or how can I use response of ec2 instance to take further action like if one ec2 is running the close it. Any help would be appreciated. I am new to NodeJs. Thanks in Advance.
What you have posted here is "backend code", or code that runs behind your server that your users will never see.
You need to add "front end code" to this system. Android apps, windows applications, and websites are all examples of "front ends".
Common nodejs libraries used to provide a web front end are:
Express
Koa
Native HTTP module
For the rest of this answer, I'll be assuming you choose express because it's the easiest for a beginner to understand, in my opinion.
A simple webserver
The simplest example of adding a webpage would look like this.
var express = require( 'express' )
var app = express()
var myAwsFetcher = require( './aws-fetcher' )
app.get( '/', function( req, res ){
myAwsFetcher( function( err, data ){
res.send( data )
})
})
app.listen( 8888, function(){
console.log( 'App is listening on localhost:8888' )
})
This way, when you run node index.js and go to http://localhost:8888, you should see in your browser:
{ InstanceStatuses:
[ { InstanceId: 'i-67441a9c',
AvailabilityZone: 'us-east-1c',
Events: [],
InstanceState: [Object],
SystemStatus: [Object],
InstanceStatus: [Object] },
{ InstanceId: 'i-feac4e0f',
AvailabilityZone: 'us-east-1b',
Events: [],
InstanceState: [Object],
SystemStatus: [Object],
InstanceStatus: [Object] } ] }
To display the response you can define:
<body>
<textarea readonly id= "textarea" style="width:400px; height:800px"></textarea>
</body>
and replace: console.log(response);
whith: document.getElementById('textarea').innerHTML = response;