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

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.

Related

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]

Javascript long integer from server is not accurate [duplicate]

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

JSON decode list of lists in Django Python

I have a list of lists (e.g. [[1,2],[3,4]]) passed from a Django view to a javascript variable and submitted with jQuery. I need to parse that variable to pull indices. The basic process is:
Add as context variable (python):
resultMsgList.append(msg)
resultMsgListJson=json.dumps(resultMsgList)
resultDict['resultMsgListJson']= resultMsgListJson
Javascript:
var resultMsgList = {{resultMsgListJson}};
var data = {'resultMsgList':resultMsgList};
$.post(URL, data, function(result){
});
Google Console gives me:
Javascript:
var resultMsgList = [["View \"S03_2005_LUZ_140814_105049_with_geom\" was successfully created!", "luz_mapfile_scen_tdm_140814_105049", "S03_2005_LUZ_140814_105049_with_geom", "C:/djangoProjects/web_output/mapfiles/ATLANTA/luz_mapfile_scen_tdm_140814_105049.map", [25, 50, 498.26708421479, 131137.057816715]]];
I copied this result to a validator, which states it is correct JSON.
The post gives me:
resultMsgList[0][]:View "S03_2005_LUZ_140814_105049_with_geom" was successfully created!
resultMsgList[0][]:luz_mapfile_scen_tdm_140814_105049
resultMsgList[0][]:S03_2005_LUZ_140814_105049_with_geom
resultMsgList[0][]:C:/djangoProjects/web_output/mapfiles/ATLANTA/luz_mapfile_scen_tdm_140814_105049.map
resultMsgList[0][4][]:25
resultMsgList[0][4][]:50
resultMsgList[0][4][]:498.26708421479
resultMsgList[0][4][]:131137.057816715
I need to get elements from this list. I currently have (python):
resultMsgListContext = request.POST.get('resultMsgListJson','')
resultMsgListContext = json.loads(resultMsgListContext)
oldMapfileName=resultMsgListContext[0][2] (+ a number of similar statements)
According to this post I then need to decode the variable in python with json.loads(), but it says there is no JSON object to be decoded. Based on the examples in the Python docs, I'm not sure why this doesn't work.
I believe the problem is that it is viewing the entire resultMsgList as a string, substantiated by the fact that there is a u' xxxxx ' in the result. That's why it is saying index out of range because you're trying to access a 2D array when it is still a string. You have to convert it to an array of strings by using json.loads.
In javascript, try passing
var data = {'resultMsgListJson':resultMsgList};
instead of
var data = {'resultMsgListJson': resultMsgListJson};
resultMsgListJson isn't a javascript variable that's defined at that point, it might be getting evaluated to undefined.
In general, in python, print the contents of resultMsgListContext before trying to do json.loads on it so you can see exactly what you're trying to parse.

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/

JSON Data format

Not very familiar with JSON data and how to create it using JavaScript.this is what i am trying
i have created two JS variables
var json={};
var json1={};
i have some certain loops to iterate data and loops like
for(firstLoop){
key=outerKey;
for(innerLook){
innerKey=innerkey;
for(lastloop){
jsonValues= create values in a java variable
}
json[innerKey]=jsonValues;
}
json1[outerKey]=JSON.stringify(json);
}
Doing this i am getting following output
Required: "{"Center":"radio_Required_Center_0,radio_Required_Center_1,","Left":"radio_Required_Left_0,"}"
which is not a valid JSON format.My idea id to create a outer-key say Required and than an inner one's in my case Center and Left
so that i can iterate each value with respect to key Center (i can break the string based on ')
i am not sure how to create correct structure and i don't want to do it on server side which can be done easily.
any solution or hint will really be helpful.
Edit
var data= JSON.stringify(json1);
giving following output
{"Required":"{\"Center\":\"radio_Required_Center_0,radio_Required_Center_1,\",\"Left\":\"radio_Required_Left_0,\"}"}
which is valid JSON data, now i need to execute some code based on the data in the JSON and here are my requirements
Fetch the outer-key (Required or there can be other also).
Fetch all values under the key Center and Left
Create array from the value retrieved from step 2 (split based on ",").
Loop through the values obtained from step 3 and execute the logic.
My real challenge is at step number 2 and 3 where i need to fetch the keys and its associated values and those key and not predefined so i can not access them based on there name.
I am thinking of a way to get key and its values without hard coding key names and execute my logic.
is it possible in by this approach or not?
If you're using a modern version of Javascript, it comes with JSON functions built-in.
var jsonString = JSON.stringify(jsobject);
...to convert a JS object into a JSON string.
(See https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/JSON/stringify)
and
var jsOject = JSON.parse(jsomString);
...to convert back in the other direction.
(see https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Global_Objects/JSON/parse)
The only time you need to worry about this not being built-in is if you're using an old browser - for example, older versions of IE. However, in this case, there are polyfill libraries like this one that you can load which will implement the above syntax for you.
If you're just trying to compose one big JSON object, you don't need to stringify one JSON object before adding it to another... So instead of doing JSON.stringify(json) you can just do json1[outerKey]=json
for(firstLoop){
key=outerKey;
for(innerLook){
innerKey=innerkey;
for(lastloop){
jsonValues= create values in a java variable
}
json[innerKey]=jsonValues;
}
json1[outerKey]=json;
}
try jsonlint.com to validate your JSON
This is valid:
{
"Center": "radio_Required_Center_0,radio_Required_Center_1,",
"Left": "radio_Required_Left_0,"
}
This is valid too:
{
"Required": {
"Center": "radio_Required_Center_0,radio_Required_Center_1,",
"Left": "radio_Required_Left_0,"
}
}
This isn't:
Required: {
"Center": "radio_Required_Center_0,radio_Required_Center_1,",
"Left": "radio_Required_Left_0,"
}
using JSON.stringify() is the right way of converting javascript objects to JSON string format. However if you want to put it in a variable you should do that first, later in the last step you convert to JSON string.
var output = { "Required": yourpreviousjsonvar },
jsonString = JSON.strinify(output);
EDIT:
You need to process the data first you probably won't even need the JSON string if I understand you right. (=> if however you already got a string you need it parsed first. Do it using JSON.parse(yourjsonstring))
Fetch the outer-key (Required or there can be other also).
Fetch all values under the key Center and Left
Create array from the value retrieved from step 2 (split based on ",").
Loop through the values obtained from step 3 and execute the logic.
having this as variable:
var a = {
"Required": {
"Center": "radio_Required_Center_0,radio_Required_Center_1,",
"Left": "radio_Required_Left_0,"
}
}
// step 1
console.log(a.Required);
// step 2
console.log(a.Required.Center);
console.log(a.Required.Left);
// step 3
var center = a.Required.Center.split(',');
var left = a.Required.Left.split(',');
// step 4
for(var i = 0; i<center.length; i++){
console.log("doing somthing with", center[i]);
}
Here is a fiddle => use Chrome/safari/Opera's developpertools and check the console to check the output. Or use firebug (in firefox) Or IE9 or greater (F12).
Use native Javascript toSource :
var obj= new Object();
var obj1= new Object();
for(firstLoop){
key=outerKey;
for(innerLook){
innerKey=innerkey;
for(lastloop){
jsonValues= create values in a java variable
}
obj.innerKey=jsonValues;
}
obj1.outerKey=obj;
}
json = obj.toSource();
json1 = obj1.toSource();

Categories