I'm using the http://blockchain.info/api/api_websocket websocket api.
My json object for each transaction looks like this:
{
"op": "utx",
"x": {
"hash": "f6c51463ea867ce58588fec2a77e9056046657b984fd28b1482912cdadd16374",
"ver": 1,
"vin_sz": 4,
"vout_sz": 2,
"lock_time": "Unavailable",
"size": 796,
"relayed_by": "209.15.238.250",
"tx_index": 3187820,
"time": 1331300839,
"inputs": [
{
"prev_out": {
"value": 10000000,
"type": 0,
"addr": "12JSirdrJnQ8QWUaGZGiBPBYD19LxSPXho"
}
}
],
"out": [
{
"value": 2800000000,
"type": 0,
"addr": "1FzzMfNt46cBeS41r6WHDH1iqxSyzmxChw"
}
]
}
}
I'm accessing the "addr" variable by using json.x.out[0].addr which prints out fine in a console.
However when I run a command through mongoose:
Game.findOne({address:json.x.out[0].addr},function (err, game) {
results in following error:
TypeError: Cannot read property 'x' of undefined
at Promise.<anonymous> (/Users/michael/Desktop/DugleyBit/app.js:176:25)
at Promise.addBack (/Users/michael/Desktop/DugleyBit/node_modules/mongoose/lib/promise.js:133:8)
at Promise.EventEmitter.emit (events.js:96:17)
at Promise.emit (/Users/michael/Desktop/DugleyBit/node_modules/mongoose/lib/promise.js:66:38)
at Promise.complete (/Users/michael/Desktop/DugleyBit/node_modules/mongoose/lib/promise.js:77:20)
at Query.findOne (/Users/michael/Desktop/DugleyBit/node_modules/mongoose/lib/query.js:1607:15)
at model.Document.init (/Users/michael/Desktop/DugleyBit/node_modules/mongoose/lib/document.js:227:11)
at model.init (/Users/michael/Desktop/DugleyBit/node_modules/mongoose/lib/model.js:196:36)
at Query.findOne (/Users/michael/Desktop/DugleyBit/node_modules/mongoose/lib/query.js:1605:12)
at exports.tick (/Users/michael/Desktop/DugleyBit/node_modules/mongoose/lib/utils.js:404:16)
Is it not a string? How can I convert it?
Thanks
Edit:
Please note that json is properly formated:
var json = JSON.parse(message);
Looks like json variable is not available in scope where you call Game.findOne.
Related
I have an object in PHP that I'm passing to Javascript in the same page. It seems to be passing through fine as a console.log statement returns the expected result but when I try to turn it into a Javascript variable the "id" is replaced with a 1, no quotation marks, rather than the expected result. If I wrap the PHP statement in the Javascript in square brackets the "id" does not change, but then it's formatted oddly. What I'm wondering is why this is occurring and if there's something I should do differently.
ETA:
Since there was some confusion:
The input is "Data," below. That is generated from the results of a SQL query by way of an array_push statement. I have included the code for each row of the SQL query and the array_push statement below, but there does not seem to be a problem with the PHP side.
My expected output is simply the data to be transferred to a JSON object on the javascript side with the appropriate variable, using the code mentioned under "Javascript." Instead I am getting something like this as console.log output:
{
DNB_number: "0"
color: "darkred"
id: 1
name: "Anonymous"
role: "Author"
size: null
type: "person"
witness_work_id: "1467"
witness_work_role_id: "1659"
}
That 1 under id is what is the issue.
There is nothing happening on the javascript side before the attempt to convert the result to a javascript variable (what you see under javascript below), so there's not much else I can tell you there. The conversion on the PHP side happens, I start my javascript, then immediately attempt to invoke it on the javascript side.
PHP code:
$person_color = "darkred";
foreach ($person_data as $row) {
$person_id = $row["person_id"];
$type = "person";
$witness_work_role_id = $row["Witness_work_role_id"];
$witness_work_id = $row["Witness_work_id"];
$person = $row["Person_name"];
$DNB = $row["Oxford_DNB_number"];
$role = $row["Role"];
$color = $person_color;
array_push($GLOBALS['person_array'], array(
'id'=>$person_id,
'witness_work_role_id'=>$witness_work_role_id,
'witness_work_id'=>$witness_work_id,
'type'=>$type,
'name'=>$person,
'DNB_number'=>$DNB,
'role'=>$role,
'color'=>$color,
'size'=> NULL
));
}
$jperson = json_encode($person_array);
Javascript code:
person_array = <?=$jperson; ?>;
Data:
[
{
"id": "1",
"witness_work_role_id": "1660",
"witness_work_id": "1468",
"type": "person",
"name": "Anonymous",
"DNB_number": "0",
"role": "Author",
"color": "darkred",
"size": null
},
{
"id": "152",
"witness_work_role_id": "1573",
"witness_work_id": "1384",
"type": "person",
"name": "Gilbert Banester",
"DNB_number": "0",
"role": "Author",
"color": "darkred",
"size": null
},
{
"id": "153",
"witness_work_role_id": "1574",
"witness_work_id": "1385",
"type": "person",
"name": "Elizabeth Plantagenet (Elizabeth of York)",
"DNB_number": "8635",
"role": "Author",
"color": "darkred",
"size": null
},
{
"id": "3",
"witness_work_role_id": "1642",
"witness_work_id": "1451",
"type": "person",
"name": "Geoffrey Chaucer",
"DNB_number": "5191",
"role": "Author",
"color": "darkred",
"size": null
},
{
"id": "7",
"witness_work_role_id": "1643",
"witness_work_id": "975",
"type": "person",
"name": "Benedict Burgh",
"DNB_number": "3390",
"role": "Author",
"color": "darkred",
"size": null
},
{
"id": "5",
"witness_work_role_id": "1659",
"witness_work_id": "1467",
"type": "person",
"name": "Anonymous",
"DNB_number": "0",
"role": "Author",
"color": "darkred",
"size": null
}
]
Let's work this out in a minimal example. Based on what you're saying, the variable is a string (of an int), and the value is correct in memory. But when you view that value via console.log you see an int instead of a string.
var test = "1";
if (typeof test == 'string') {
console.log('yes, it is a string');
} else {
console.log('no, it is not a string');
}
If you copy/paste the above into your JS console and run it, you'll see the message yes, it is a string. This proves that it is a string in memory.
another way to test this value is to just run test in your console, and you should see "1" output.
But now, when we use console.log to inspect the value:
console.log(test) outputs 1
Another example without a variable: console.log("123") outputs 123, not "123"
What's apparently happening is just an artifact of console.log. See Javascript console.log(object) vs. concatenating string for more examples and explanations. https://dmitripavlutin.com/console-log-tips/ lists some more options. For instance, if you create an object containing your variable and output that: console.log({test}) will output {test: "1"}, so you can see again that test is a string with the value "1".
I am recieving a JSON response back from an API which isnt in the right format to be parsed.
I have tried to add the missing key at the start and it won't allow it.
[
{
"deviceId": "9092eab10f4",
"name": "temperature",
"timestamp": "2017-06-13T13:19:59.673Z",
"value": 21.5
},
{
"deviceId": "9092eab10f4",
"name": "temperature",
"timestamp": "2017-06-13T13:19:59.673Z",
"value": 21.5
}
]
I would like this to have the missing key and additional curly bracket like so:
{
"data": [
{
"deviceId": "9092eab10f4",
"name": "temperature",
"timestamp": "2017-06-13T13:19:59.673Z",
"value": 21.5
},
{
"deviceId": "9092eab10f4",
"name": "temperature",
"timestamp": "2017-06-13T13:19:59.673Z",
"value": 21.5
}
]
}
I'm not sure if the response you're getting is a string or an object.
Here's a fiddle that considers both scenarios and logs your expected output to the console.
https://jsfiddle.net/6yu9ngf5/2/
I've used JSON.parse(<string>) for the case where the response is string.
For other case I just added data key to your response.
Simple object assign?
const properResponse = Object.assign({}, {data: [response.json()]});
...assuming response is fetch, or similar with a json method which returns the response object.
I am having difficulty with a pulling some data from an API for a school project using Jquery.
If I use the following coinmaketcap API I get the following response
https://api.coinmarketcap.com/v1/ticker/bitcoin/
[
{
"id": "bitcoin",
"name": "Bitcoin",
"symbol": "BTC",
"rank": "1",
"price_usd": "8854.92",
"price_btc": "1.0",
"24h_volume_usd": "6759730000.0",
"market_cap_usd": "150480289107",
"available_supply": "16993975.0",
"total_supply": "16993975.0",
"max_supply": "21000000.0",
"percent_change_1h": "-0.13",
"percent_change_24h": "0.12",
"percent_change_7d": "8.3",
"last_updated": "1524459272"
}
]
I get am able to get the symbol for Bitcoin and place it into a variable by using this code
> $.getJSON('https://api.coinmarketcap.com/v1/ticker/btc/',
> function(data){
> var symbol = (data[0].symbol)
> })
Once I have it I can place it in a div.
However when I use cryptocompare API I don't get anything back
https://min-api.cryptocompare.com/data/coin/generalinfo?fsyms=BTC,&tsym=USD
$.getJSON('https://min-api.cryptocompare.com/data/coin/generalinfo?fsyms=BTC&tsym=USD', function(data){
var symbol = (data[0].Internal)
});
This is the response -
{
"Message": "Success",
"Type": 100,
"Data": [
{
"CoinInfo": {
"Id": "1182",
"Name": "BTC",
"FullName": "Bitcoin",
"Internal": "BTC",
"ImageUrl": "/media/19633/btc.png",
"Url": "/coins/btc/overview",
"Algorithm": "SHA256",
"ProofType": "PoW",
"NetHashesPerSecond": 27483320229.3688,
"BlockNumber": 518932,
"BlockTime": 600,
"BlockReward": 12.5,
"Type": 1,
"DocumentType": "Webpagecoinp"
},
"ConversionInfo": {
"Conversion": "direct",
"ConversionSymbol": "",
"CurrencyFrom": "BTC",
"CurrencyTo": "USD",
"Market": "CCCAGG",
"Supply": 16986575,
"TotalVolume24H": 380849.0498955779,
"SubBase": "5~",
"SubsNeeded": [
"5~CCCAGG~BTC~USD"
],
"RAW": [
"5~CCCAGG~BTC~USD~4~8875.23~1524460635~0.00477012~42.152119404000004~231254719~10820.885574747872~96327075.76938197~66326.58563159907~593473019.8524572~8823.46~8917.05~8804.2~8864.31~9065~8780.91~Bitfinex~7ffe9"
]
}
}
]
}
Why is the second piece of code not working? Please help!
The second API is returning an object (in JSON format), not an array - see how the first character is { and how it has keys and values? You need to access the appropriate property to get the value you want. [0] notation indicates you're trying to access the first element of the array, but the outer object is not an array in this situation.
$.getJSON('https://min-api.cryptocompare.com/data/coin/generalinfo?fsyms=BTC&tsym=USD',
function(data){
var symbol = data.Data[0].CoinInfo.Internal;
});
In both the cases, we are getting data in different form. So, To get the 'BTC' in variable .
for 1st case -> symbol = data[0] ['symbol']
for 2nd case -> symbol = data['Data'][0]['CoinInfo']['Internal']
one is an [array of JSON] while other is an [object having key 'Data' with array value].
I have the following JSON:
{
"list": {
"q": "raw",
"sr": "28",
"ds": "Standard Reference",
"start": 0,
"end": 1,
"total": 1391,
"group": "",
"sort": "n",
"item": [
{
"offset": 0,
"group": "Poultry Products",
"name": "Chicken, broilers or fryers, dark meat, thigh, meat only, raw",
"ndbno": "05096",
"ds": "SR"
}
]
}
}
But when I try to access elements in this json i keep getting undefined error... I already checked if the JSON is valid and yes the json is valid!
Maybe I am accesing the JSON wrong? The JSON is stored in a variable called result. This is how I tried so far:
console.log(result.list.ds);
I also tried:
console.log(result["0"].list.ds);
but both solutions give me the following error:
Uncaught TypeError: Cannot read property 'ds' of undefined
Why is this happening? Any tips or suggestions are welcome!
Is your JSON stored in your variable as a string? Try:
console.log(JSON.parse(result).list.ds)
The reason I ask is that the text Uncaught TypeError: Cannot read property 'ds' of undefined tells me that your result variable does not have a list property, which your JSON clearly would if it were an object, but it most assuredly would not if you had accidentally forgotten to parse your JSON string.
Your JSON is valid and if you are accessing the ds property inside list object. Your syntax console.log(result.list.ds); is correct.
But, If you are trying to access the ds property inside the item array then you have to iterate the array to get the ds property.
DEMO
var result = {
"list": {
"q": "raw",
"sr": "28",
"ds": "Standard Reference",
"start": 0,
"end": 1,
"total": 1391,
"group": "",
"sort": "n",
"item": [{
"offset": 0,
"group": "Poultry Products",
"name": "Chicken, broilers or fryers, dark meat, thigh, meat only, raw",
"ndbno": "05096",
"ds": "SR"
}]
}
};
var res = result.list.item.map(function(elem) {
return elem.ds;
})
console.log(res);
I'm using Jquery GET to fetch some JSON data that looks like this:
{
"list": {
"meta": {
"type": "resource-list",
"start": 0,
"count": 1
},
"resources": [
{
"resource": {
"classname": "Quote",
"fields": {
"change": "-0.400002",
"chg_percent": "-1.200485",
"day_high": "33.779999",
"day_low": "32.549999",
"issuer_name": "PayPal Holdings, Inc.",
"issuer_name_lang": "PayPal Holdings, Inc.",
"name": "PYPL",
"price": "32.919998",
"symbol": "PYPL",
"ts": "1442606400",
"type": "equity",
"utctime": "2015-09-18T20:00:00+0000",
"volume": "16488139",
"year_high": "42.550000",
"year_low": "30.000000"
}
}
}
]
}
}
I would like to get the value of day_high. Using Jquery I do:
jQuery.ajax({
url: "http://****.com",
type: "GET",
dataType: "json",
async: false,
success: function (data) {
var x = JSON.stringify(data.list.resource.change);
$("p.name").append(x);
console.log(x.change);
}
});
In my console I get:
Uncaught TypeError: Cannot read property 'change' of undefined
I also tried an array approach like data.list.resource[0].change But this outputs:
Uncaught TypeError: Cannot read property '0' of undefined
First, the variable x cannot be interpreted as JSON with your console logging statement because JSON.stringify converts it to a string. Second, it looks like you have your path mixed up. It should be data.list.resources[0].resource.fields.change.
You can try this:
var x = JSON.stringify(data.list.resources[0].resource.fields.change);
The error was with your path.