Reputation: 397
How can i solve this error JSON.parse: unexpected character at line 1 column 2 of the JSON data
I am trying to display specific JSON content from a ticker link, but unfortunately couldn't get it to work, as the error keep popping.
HTML
<input id="currency1" type="text">
<span>Currency1</span>
<input id="currency2" type="text">
<span>Currency2</span>
<div>
<button type="button" onclick="refreshPrice()">
Refresh Price
</button>
<span id="lastPrice"></span>
</div>
JSON Response from the Ticker Link
{"ticker":{"high":"16985100","low":"16730900","last":"16879000"}}
JAVASCRIPT
var lastPrice;
function refreshPrice() {
$lastPrice = $('#lastPrice');
$lastPrice.html("");
$.get("https://example.com") //Ticker link
.then(function (data) {
lastPrice = JSON.parse(data).ticker.last - 100000;
lastPrice.html(lastPrice);
});
}
refreshPrice();
$('#currency2').keyup(function() {
currency2Val = parseFloat($(this).val());
if (currency2Val) {
currency1Val = currency2Val * lastPrice;
$('#currency1').val(parseInt(currency1Val));
}
else {
$('#currency1').val("");
}
});
$('#currency1').keyup(function() {
currency1Val = parseInt($(this).val());
if (currency1Val) {
currency2Val = currency1Val / lastPrice;
$('#currency2').val(currency2Val.toFixed(8));
}
else {
$('#currency2').val("");
}
});
Any help would be appreciated, thanks
Upvotes: 1
Views: 6550
Reputation: 1487
Response is already in JSON format, you shouldn't be passing it through JSON.parse, as JSON.parse expects input to be a stringify JSON
Try this :
lastPrice = data.ticker.last - 100000;
Upvotes: 0
Reputation: 1075755
Assuming the ticker responds with the correct Content-Type
header, jQuery will already have parsed the response for you. So remove the JSON.parse
:
$.get("https://example.com") //Ticker link
.then(function (data) {
lastPrice = data.ticker.last - 100000;
$lastPrice.html(lastPrice);
});
(I've also included a fix there for the issue Jaromanda X pointed out, using lastPrice
rather than $lastPrice
.)
From the documentation:
dataType
(default: Intelligent Guess (xml, json, script, or html))Type: String
The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response (an XML MIME type will yield XML, in 1.4 JSON will yield a JavaScript object, in 1.4 script will execute the script, and anything else will be returned as a string).
Upvotes: 1
Reputation: 2128
Try to remove JSON.parse,
var lastPrice;
function refreshPrice() {
$lastPrice = $('#lastPrice');
$lastPrice.html("");
$.get("https://example.com") //Ticker link
.then(function (data) {
debugger;
lastPrice = data.ticker.last - 100000;
lastPrice.html(lastPrice);
});
}
Put a debugger as well, to see what is your response.
Upvotes: 2