Javascript long integer from server is not accurate [duplicate] - javascript

This question already has answers here:
Javascript - convert an EXTRA LARGE Number to string in JSON before the default parsing
(4 answers)
Closed 4 years ago.
I've got an API which I make a get request to fetch data. When i try to save the Id, I see Javascript round the last digit of it and it makes my program to break!
I see THIS QUESTION but how can I save each Id as string?
I'm using a global array to store the selected items' data so, anyway to save one attribute of a JSON in string?
I'm going to have (for example) 3 items and make another get request for each Id:
axios.get(`http://api.nemov.org/api/v1/Market/Symbol/${this.props.ID}`)
One of those Ids, is: 9481703061634967 but JS convert that to 9481703061634968 so the get request is broken!
Any solution?

See my solution on this question:
Transform the response to string, then apply a repalce with a regex to
convert Id field to string type:
const axios = require("axios");
axios.get(url, {transformResponse: [data => data]}).then((response) => {
let parsed = JSON.parse(response.data.replace(/"Id":(\d+),/g, '"Id":"$1",'))
console.log(parsed)
});

Use this:
let strId = this.props.ID.toString();
axios.get(`http://api.nemov.org/api/v1/Market/Symbol/${strId}`)

Related

Put data from a JSON object which was created in php into an array in a different Javascript file [duplicate]

This question already has answers here:
JSON encode MySQL results
(16 answers)
How do I pass variables and data from PHP to JavaScript?
(19 answers)
Closed 7 months ago.
I need to how I can use data that I fetched from the database and put into a JSON Object inside a php-file in another (Javascript)-File, where the data is supposed to end up inside an array.
function loadApplicationList()
{
$email = $_GET['email'];
$listcontent = queryDB("
SELECT Application.FavRank, Proposal.Title, Proposal.pdfName, RegisteredUser.Name
FROM Application
LEFT JOIN user_application
ON Application.ID = user_application.ID AND user_application.eMail = '$email'
LEFT JOIN Proposal
ON Proposal.ID = Application.Proposal_ID
LEFT JOIN RegisteredUser
ON RegisteredUser.eMail = Proposal.AuthorEmail;");
$encodeContent = json_encode($listcontent);
}
?>
Above is the php code, below the JS code
let data = [
// this array is supposed to contain the data from the JSON Object
];
I should also mention that I am new to these languages, so I might've already 'found' the right answer during my hour long research online but wasn't capable to identify it. Thanks for your help in advance.

Creating dictionary using python from javascript var data [duplicate]

This question already has answers here:
Convert [key1,val1,key2,val2] to a dict?
(12 answers)
Make dictionary from list with python [duplicate]
(5 answers)
Convert list into a dictionary [duplicate]
(4 answers)
Closed 4 years ago.
trying to figure out how to do this and have yet to find a good solution. I pulled this data out of an XML response. It was in a var tag. Now what I would like to do is create a dictionary out of it. The domain.com should be paired with the number right listed behind it.
This is the data:
[
'cb131.domain1.com', '147827',
'cb143.domain2.com', '147825',
'cb175.domain1.com', '147454',
'cb190.domain.com', '146210',
'cb201.domain.com', '146208',
'cb219.domain.com', '146042',
'cb225.domain.com', '146282',
'cb900.domain.com', '148461',
'cb901.domain.com', '148493',
'cb902.domain.com', '148495',
'cb903.domain.com', '148497',
'cb904.domain.com','148499',
'cb905.domain.com', '148501',
'cb906.domain.com', '148503',
'cb907.domain.com', '148505',
'cb908.domain.com', '148507',
'cb909.domain.com', '148509'
]
So for example cb131.domain1.com should be paired with 147827, cb143.domain2.com paired with 147825 and so on.
Drawing a blank on a good quick solution on how to do this. Hopefully someone can help.
Thanks!
Edited with answer I choose below:
I choose this answer and also to help anyone else I add a nice way to print out the results (data is the string I obtained):
import ast
i = iter(ast.literal_eval(data))
dic = dict(zip(i, i))
for key , value in dic.items():
print(key, " :: ", value)
This should do it. Assuming the list is saved to a variable l:
keys = l[::2]
vals = l[1::2]
dic = dict(zip(keys, vals))
You can create an iterator from the list after using ast.literal_eval to parse it from the input text, zip the iterator with itself, and pass the generated sequence of tuples to the dict constructor:
import ast
i = iter(ast.literal_eval(data))
dict(zip(i, i))
Assuming you have the above in a python array called data, you can do:
new_data = []
for i in range(0, len(data), 2):
new_data.append((data[i], data[i+1]))
Now new_data would be a list of tuples. You could certainly create a better data structure to hold these pairs if you want.
I do not yet know Python that I can write a snippet, but:
initialize an empty dictionary in Python
create a for loop counting index from 0 to length of your array in steps of two.
inside add a dictionary entry with key of value at index and value at index + 1
perhaps check for duplicates
Does this answer help you?
This is Python - quickly google'd:
dictionary = { }
for idx in range(0, len(data), 2)
dictionary[data[idx]] = data[idx + 1]

String into array (nodejs) [duplicate]

This question already has answers here:
Convert string array representation back to an array
(3 answers)
Closed 5 years ago.
I have a string of integers
str = "[7,2,7,7,2,7,7,4,3,2]"
and i want to get an array so that i can manipulate the data easily, but i have no idea how to do it. Can you help me ? I'm sure it's a basic task but i am not very familiar with node.
Thank you.
Try JSON.parse(yourStr). Alternately:
yourString.substr(1,arr.length-2).split(",").map((el) => {
return parseInt(el)
})
Looks like JSON, parse it with JSON.parse
numbers = JSON.parse("[7,2,7,7,2,7,7,4,3,2]")

Basic JQuery API call - how to specify part of the response? [duplicate]

This question already has answers here:
parsing out ajax json results
(3 answers)
Closed 9 years ago.
I'm very, very new to APIs (an hour in), and I'm just trying to get to the point where I can output a single part of an API response into console.log - and work from there.
Here's the working code which grabs all the data (for example, to display the last price in Bitcoin:
$.ajax({
url: "https://api.bitcoinaverage.com/ticker/all",
dataType: 'json',
success: function(results){
var gpbvalue = results;
console.log(gpbvalue);
}
});
And here's the data itself: https://api.bitcoinaverage.com/ticker/all
How would I specify just the 'last' value under GPB, rather than outputting the entire set of data?
Thank you so much for any help!
This is what you want.
console.log(results.GBP.last);
var gbpvalue = results.GBP.last;
or results["GBP"]["last"], both are equivalent.
The response is a JSON where the first key is a country code and the last value is a key under that. If you wanted to pick a specific last value you could access it like this:
console.log(results['AUD']['last']);
Or if you wanted all last keys you could do this:
for(key in results) {
console.log(results[key]['last']);
}
You can use dot notation but one of the keys 24h_avg is an invalid variable name (vars can't start with numbers) so named index notation is a better habit to get into.

Accessing a two dimensional JSON array with Javascript [duplicate]

This question already has answers here:
Closed 10 years ago.
Possible Duplicate:
I have a nested data structure / JSON, how can I access a specific value?
I am using the US Census API and end up with a two dimensional json array from a jQuery.get() request. My result (data) looks like this:
[["P0010001","NAME","state","county","tract"], ["2703","Census Tract 4001.01","17","119","400101"], ["5603","Census Tract 4001.02","17","119","400102"], ["4327","Census Tract 4002","17","119","400200"]]
It looks exactly like a two dimensional javascript array, but I cannot access it like one when I try:
var population = data;
alert(population[1][0]);
Is there a way to convert the json array into a javascript array, or to convert it to a string, which could then be put into an array?
Use JSON.parse:
var population = JSON.parse(data);
alert(population[1][0]);
JsFiddle: http://jsfiddle.net/6CGh8/

Categories