I have question, I hava a json with some information and I need to get a specific value, for example the Location, I had created a function but it doesn´t work fine, I get this error message about the " "
SyntaxError: invalid label
"location" : "Austin-Bergstrom International Airport,
The function is this one
function lee_json() {
var temp = ('http://df9e7c46aa4c80573717-1199cc892ebab574a120721e4772cd8b.r11.cf2.rackcdn.com/services/aus.json');
temp2 = temp.location;
alert(temp2);
console.log(temp);
console.log(temp.location);
}
and the Json is this one
{
"location" : "Austin-Bergstrom International Airport, Tx",
"city" : "Austin",
"state" : "Tx",
"dewPointC" : 4.4,
"visibilityMiles" : 10,
"rainChance" : "10%"
}
What can be the problem ?
Regards,
try this http://msdn.microsoft.com/en-us/library/ie/cc836466(v=vs.94).aspx this might be the kind of answer you're looking
if i assume you are using jquery you can use this
http://api.jquery.com/jQuery.getJSON/
Assuming 1) you are running this on the same domain where the json is hosted, 2) you have jquery, 3) the result is a json object, not an array, this is a legit example of getting a field:
function getData(aLink) {
$.getJSON(aLink,
function(data) {
console.log(data.location);
});
}
getData("http://df9e7c46aa4c80573717-1199cc892ebab574a120721e4772cd8b.r11.cf2.rackcdn.com/services/aus.json");
Related
I am using JSON to retrieve stock market data from an API (FMP cloud) for my Google Sheets spreadsheet, but don't know how to fetch a specific piece of data off of the API webpage. Here are the contents of the webpage I'm trying to pull from:
[ {
"symbol" : "AMC",
"name" : "AMC Entertainment Holdings, Inc.",
"price" : 5.60000000,
"changesPercentage" : -0.18000000,
"change" : -0.01000000,
"dayLow" : 5.55000000,
"dayHigh" : 5.97000000,
"yearHigh" : 20.36000000,
"yearLow" : 1.91000000,
"marketCap" : 1898808704.00000000,
"priceAvg50" : 4.95848460,
"priceAvg200" : 4.37841750,
"volume" : 39477325,
"avgVolume" : 120395740,
"exchange" : "NYSE",
"open" : 5.72000000,
"previousClose" : 5.61000000,
"eps" : -34.81800000,
"pe" : null,
"earningsAnnouncement" : "2020-11-02T16:15:00.000+0000",
"sharesOutstanding" : 339072983,
"timestamp" : 1613160110
} ]
If I use the cell script =IMPORTJSON("https://fmpcloud.io/api/v3/quote/AMC/?apikey=examplekey", "/price","") (I substituted out my real API key) it fetches all data with the word "price" in it, meaning price, priceAvg50, and priceAvg200. It looks like this:
Avg50 Avg200
5.59 4.9584846 4.3784175
If I just want price, which is the first piece of data (5.59), how should I modify the script in the cell? Hopefully this question makes sense. Thanks for your time.
From your following 2 reply comments,
When I try this, it restricts what I can fetch to just the price. All cells with script looking to fetch other things come up as an error. Is there a way to bypass that?
A sample output would be two cells. In cell 1, I would write =IMPORTJSON("https://fmpcloud.io/api/v3/quote/AMC/?apikey=examplekey", "/price", "noHeaders") which ideally would show me the price of the stock. In cell 2, I would write =IMPORTJSON("https://fmpcloud.io/api/v3/quote/AMC/?apikey=examplekey", "/changesPercentage", "noHeaders"), which would show me the percent change of the stock price.
I understood your goal as follows.
You want to retrieve the values from the JSON data in your question by giving the property names.
Although, unfortunately, I cannot understand about your current script of IMPORTJSON, if the structure of the data from your URL is always the same, how about directly creating a script for the URL you want to use?
Sample script:
Please copy and paste the following script to the script editor of Google Spreadsheet.
function SAMPLE(url, keys) {
const obj = JSON.parse(UrlFetchApp.fetch(url).getContentText());
return [keys.split(",").map(k => obj[0][k.trim()] || "")];
}
When you use this script, please put =SAMPLE("https://fmpcloud.io/api/v3/quote/AMC/?apikey=examplekey", "price") and =SAMPLE("https://fmpcloud.io/api/v3/quote/AMC/?apikey=examplekey", "changesPercentage").
If you want to retrive the multiple values by one custom forumula, please put =SAMPLE("https://fmpcloud.io/api/v3/quote/AMC/?apikey=examplekey", "price,changesPercentage").
When above sample data is used, this formula returns 5.6, -0.18 to a row.
If the property name which is not existing in the data from URL is given, the empty value is returned.
References:
Custom Functions in Google Sheets
Class UrlFetchApp
function hexhead() {
const d=JSON.parse('[ { "symbol" : "AMC", "name" : "AMC Entertainment Holdings, Inc.", "price" : 5.60000000, "changesPercentage" : -0.18000000, "change" : -0.01000000, "dayLow" : 5.55000000, "dayHigh" : 5.97000000, "yearHigh" : 20.36000000, "yearLow" : 1.91000000, "marketCap" : 1898808704.00000000, "priceAvg50" : 4.95848460, "priceAvg200" : 4.37841750, "volume" : 39477325, "avgVolume" : 120395740, "exchange" : "NYSE", "open" : 5.72000000, "previousClose" : 5.61000000, "eps" : -34.81800000, "pe" : null, "earningsAnnouncement" : "2020-11-02T16:15:00.000+0000", "sharesOutstanding" : 339072983, "timestamp" : 1613160110} ]');
console.log(d[0].timestamp)
}
7:12:44 PM Notice Execution started
7:12:44 PM Info 1613160110
7:12:45 PM Notice Execution completed
I am studying quasar at the moment, and I want to know how to export a table to JSon. I have data in JSonimported and I want to get output in JSon too.
Now I'm using JSON.stringify to get data of my table, but that gives all data in a single line in JSon.
Here's a piece of my code in quasar :
exportTable() { const status = exportFile('table.json', JSON.stringify(this.data), 'text/json')}
and it gives me :
[{"Name":"xxx","Adress":"xxx","Zip code":"xxx"},{"Name":"yyy","Adress":"yyy","Zip code":"yyy"}]
What I want to output :
[{
"Name":"xxx",
"Adress":"xxx",
"Zip code":"xxx"
},
{
"Name":"yyy",
"Adress":"yyy",
"Zip code":"yyy"
}]
How can I get this ?
If I understood correctly, you want to use:
JSON.stringify(this.data, null, 4)
Where the last argument (4) is the spacing you desire.
You can have a look at JSON.stringify official documentation
const data = [{"Name":"xxx","Adress":"xxx","Zip code":"xxx"},{"Name":"yyy","Adress":"yyy","Zip code":"yyy"}]
console.log(JSON.stringify(data, null, 4))
How do I access the JSON array to display the output of "AdjustedScheduleTime" from the Trip section?
I got it working for StopLabel as shown below, but I'm struggling to access AdjustedScheduleTime.
I tried the following:
["GetNextTripsForStopResponse"]["GetNextTripsForStopResult"]["Route"]["RouteDirection"]["Trips"]["Trip"]["AdjustedScheduleTime"]
but doesn't work.
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let parameters = [
"appID": "5rt5rydg", //incorrect appID
"apiKey": "3b5fb15rdgy5454hdrfhr", //incorrect apiKey
"routeNo": "14",
"stopNo": "8600",
"format": "JSON"
]
AF.request("https://api.octranspo1.com/v1.2/GetNextTripsForStop?", method: .post, parameters: parameters,encoding:
URLEncoding.httpBody, headers: nil).responseJSON{ response in
let swiftyJsonVar = JSON(response.result.value!)
print(swiftyJsonVar)
if let busInfo = swiftyJsonVar["GetNextTripsForStopResult"]["StopLabel"].string {
print(": ",busInfo)
print("Label1: ", self.label1.text = busInfo)
}
}
}
This is the results:
{
"GetNextTripsForStopResult" : {
"Error" : "",
"Route" : {
"RouteDirection" : {
"RouteLabel" : "St-Laurent",
"Error" : "",
"RequestProcessingTime" : "20190112151425",
"Trips" : {
"Trip" : [
{
"AdjustmentAge" : "0.38",
"GPSSpeed" : "0.5",
"Latitude" : "45.429457",
"Longitude" : "-75.684117",
"TripDestination" : "St-Laurent",
"LastTripOfSchedule" : false,
"TripStartTime" : "14:31",
"BusType" : "4LB - IN",
"AdjustedScheduleTime" : "11"
},
{
"AdjustmentAge" : "4.32",
"GPSSpeed" : "0.5",
"Latitude" : "45.413749",
"Longitude" : "-75.689748",
"TripDestination" : "St-Laurent",
"LastTripOfSchedule" : false,
"TripStartTime" : "14:46",
"BusType" : "4LB - IN",
"AdjustedScheduleTime" : "22"
},
{
"AdjustmentAge" : "0.55",
"GPSSpeed" : "31.3",
"Latitude" : "45.399587",
"Longitude" : "-75.727631",
"TripDestination" : "St-Laurent",
"LastTripOfSchedule" : false,
"TripStartTime" : "15:01",
"BusType" : "4L - IN",
"AdjustedScheduleTime" : "37"
}
]
},
"RouteNo" : 14,
"Direction" : "Eastbound"
}
},
"StopLabel" : "MCARTHUR \/ IRWIN MILLER",
"StopNo" : "8600"
}
}
: MCARTHUR / IRWIN MILLER //This is the desired output for StopLabel
Ok, so do you explain JSON. Here's a shot.
First some rules:
When you see opening { it means dictionary, you have to pick a key next
When you see opening [ it means array. you have to pick an index
When you see "SomeString": its a key in an array.
Dictionaries have keys, arrays have index. Pick accordingly..
So when we walk through this response:
We see that we start with {. We have a dictionary! We're expecting to see some keys next.
So lets pick a key: We only have one and it's "GetNextTripsForStopResult". so far we have: swiftyJsonVar["GetNextTripsForStopResult"]
We now look at the content of "GetNextTripsForStopResult". We see it's also a dictionary. Again we should have some keys. We do. We have Error, Route, StopLabel and more. Let's pick a key. Since we're trying to get to a "AdjustedScheduleTime", lets pick Route. so far we have ["GetNextTripsForStopResult"]["Route"]
Now lets look at the contents of Route. Its a dictionary again.
Again we pick a key and keep repeating till we hit Trip. You should have ["GetNextTripsForStopResult"]["Route"]["RouteDirection"]["Trips"]["Trip"]
Lets look at what we have in Trip Whats this?..its an array!
We have to pick an index now. We need to chose somehow. Thats the tricky part. In order to do that we need some more information. So lets just ARBITRARILY chose one. Lets take the last one. so we have: ["GetNextTripsForStopResult"]["Route"]["RouteDirection"]["Trips"]["Trip"][2]
Now we can get our final key AdjustedScheduleTime. So let's pick it!
["GetNextTripsForStopResult"]["Route"]["RouteDirection"]["Trips"]["Trip"][2]["AdjustedScheduleTime"]
Keep in mind:
These hard coded indexes are almost NEVER what you want. Maybe you need to show all the AdjustedScheduleTime to the user or let the user chose one, or add all of them up. That really depends on your application and what you're trying to accomplish. I chose the last index (2) arbitrarily without having any knowledge of your application, the api you're calling and what you're trying to achieve. Its VERY possible that you don't want the last index.
I'm having a problem with querying a MongoDB dataset ("On Street Crime in Camden" from data.gov.uk)
The database name is Crime_Data_in_Camden and the collection name is Street_Crime_Camden. The query to find all records, db.Street_Crime_Camden.find(), works fine but anything else returns nothing at
all. Here is a portion of the metadata:
{
"id" : 509935,
"name" : "Ward Name",
"dataTypeName" : "text",
"fieldName" : "ward_name",
"position" : 13,
"renderTypeName" : "text",
"tableColumnId" : 258836,
"width" : 100,
"cachedContents" : {
"largest" : "West Hampstead",
"non_null" : 79813,
"null" : 0,
"top" : [ {
"item" : "Regent's Park",
"count" : 20
}, {
"item" : "Swiss Cottage",
"count" : 19
}, {
"item" : "Holborn and Covent Garden",
"count" : 18
}
}
}
I've tried 3 attempts at a basic query:
db.Street_Crime_Camden.find({"ward_name":"West Hampstead"});
db.Street_Crime_Camden.find({'meta.ward_name':'West Hampstead'});
db.Street_Crime_Camden.find({meta:{ward_name:"West Hampstead"} });
According to any documentation or tutorial that I've seen any of these approaches should be valid. And I know that there are hundreds of rows (or documents) that match those terms, so why are these queries returning nothing? Advice would be appreciated.
The common theme in the three aproaches you tried is some form of ward_name = West Hampstead but there is no attribute named ward_name in the document you shared with us.
Based on the document you show in your question the only way of addressing an attribute with the value West Hampstead is:
db.Street_Crime_Camden.find({"cachedContents.largest": "West Hampstead"});
For background; you address attributes in your documents by using dot notation so the document you included in your question could be found by any of the following find commands:
db.Street_Crime_Camden.find({"name": "Ward Name"});
db.Street_Crime_Camden.find({"position": 13});
db.Street_Crime_Camden.find({"cachedContents.top.item": "Swiss Cottage"});
db.Street_Crime_Camden.find({"cachedContents.top.1.count": 20});
... etc
These examples might help you to understand how to form find criteria. The MongoDB docs are also useful.
I would like to read a json file where the sutructure is like below. I tried fromJson but it just read the first block. Can you help me on specify the delimiter to read all the file?
Thank you so much
json_data <- fromJSON(paste(readLines("C:C:/Users/aa/Data-test.json"), collapse=""))
Warning message:
In readLines("C:/Users/aa/Data-test.json") :
incomplete final line found on 'C:/Users/jsalim/Desktop/Docapost_20160718/FILES/Extract-Morgane_1307/Data-device2.json'
{
"id" : "aaa",
"dateModification" : "2016-06-04T04:29:30Z",
"active" : true,
.....
}
{
"id" : "bbbb",
"dateModification" : "2016-06-04T04:29:30Z",
"active" : true,
.....
}
{
"id" : "ccc",
"dateModification" : "2016-06-04T04:29:30Z",
"active" : true,
.....
}
I believe that as in the answer suggested in this question, you just need to enter a carriage return at the end of the line (that is, there should be a single empty line at the end of your file). This worked for me in the same scenario.