Accessing items in a list in AppleScript? - json

I'm trying to access items in a list via AppleScript. Try as I might, I can't seem to access them. I've pasted my code below
tell application "JSON Helper"
set result to fetch JSON from "https://newsapi.org/v2/top-headlines?sources=bbc-news&pageSize=1&apiKey=X"
set news to title of articles of result
end tell
set result_string to news & ""
Note, I've removed my api key. The api format is :
{"status":"ok","totalResults":10,"articles":[{"source":{"id":"bbc-news","name":"BBC News"},"author":"BBC News","title":"Trump urges Israeli 'care' on settlements","description":"The US president also casts doubt on whether the Palestinians or Israel are ready to talk peace.","url":"http://www.bbc.co.uk/news/world-middle-east-43025705","urlToImage":"https://ichef.bbci.co.uk/news/1024/branded_news/165CD/production/_99979519_044058382.jpg","publishedAt":"2018-02-11T16:47:27Z"}]}
I'm trying to access title but I keep getting "can't get title".
Any input would be much appreciated. Thanks!

Using the sample JSON data you gave, I used this command:
tell application "JSON Helper" to read JSON from ¬
"{
\"status\": \"ok\",
\"totalResults\": 10,
\"articles\": [
{
\"source\": {
\"id\": \"bbc-news\",
\"name\": \"BBC News\"
},
\"author\": \"BBC News\",
\"title\": \"Trump urges Israeli 'care' on settlements\",
\"description\": \"The US president also casts doubt on whether the Palestinians or Israel are ready to talk peace.\",
\"url\": \"http://www.bbc.co.uk/news/world-middle-east-43025705\",
\"urlToImage\": \"https://ichef.bbci.co.uk/news/1024/branded_news/165CD/production/_99979519_044058382.jpg\",
\"publishedAt\": \"2018-02-11T16:47:27Z\"
}
]
}"
to retrieve an AppleScript record. Pretty-printing it as I have above, however, you might already be able to see that articles is a list (containing one item). Therefore, whilst this:
set news to title of articles of result
produces an error, this:
set news to title of item 1 of articles of result
retrieves the correct datum.

Related

How to print multiple specific JSON values with Python?

I am attempting to print values from an API via JSON response. I was successful when I tried to print the first and foremost "live" value of the response, but I started running into problems when I tried printing anything other than the "live" value. Below is a sample of what I usually receive from the API, and my goal here is to print out only every visible "name" values.
{
"live":[
{
"id":203003098,
"yt_video_key":"K0uWjPoiMRY",
"bb_video_id":"None",
"title":"【Minecraft】Nature, Please Guide Me! ft. #Ceres Fauna Ch. hololive-EN #holoCouncil",
"thumbnail":"None",
"status":"live",
"live_schedule":"2021-09-14T02:00:00.000Z",
"live_start":"2021-09-14T02:00:51.000Z",
"live_end":"None",
"live_viewers":11000,
"channel":{
"id":2260367,
"yt_channel_id":"UC3n5uGu18FoCy23ggWWp8tA",
"bb_space_id":"None",
"name":"Nanashi Mumei Ch. hololive-EN",
"photo":"https://yt3.ggpht.com/MI8E8Wfmc_ngNZXUwu8ad0D-OtqDhmqGVULEu25z-ccscwzJpAw-7ewFXzZYLK2jHB9d5OgQDq4=s800-c-k-c0x00ffffff-no-rj",
"published_at":"2021-07-26T15:45:01.162Z",
"twitter_link":"nanashimumei_en",
"view_count":4045014,
"subscriber_count":281000,
"video_count":14
}
},
{
"id":202920144,
"yt_video_key":"owk8w59Lcus",
"bb_video_id":"None",
"title":"【Undertale】平和なPルートでハッピーエンド目指す!【雪花ラミィ/ホロライブ】",
"thumbnail":"None",
"status":"live",
"live_schedule":"2021-09-14T00:00:00.000Z",
"live_start":"2021-09-14T00:04:22.000Z",
"live_end":"None",
"live_viewers":6200,
"channel":{
"id":31879,
"yt_channel_id":"UCFKOVgVbGmX65RxO3EtH3iw",
"bb_space_id":"None",
"name":"Lamy Ch. 雪花ラミィ",
"description":"ホロライブ所属。\n人里離れた白銀の大地に住む、雪の一族の令嬢。\nホロライブの笑顔や彩りあふれる配信に心を打たれ、\nお供のだいふくと共に家を飛び出した。\n真面目だが世間知らずで抜けたところがある。\n\n\n\nお問い合わせ\nカバー株式会社:http://cover-corp.com/ \n公式Twitter:https://twitter.com/hololivetv",
"photo":"https://yt3.ggpht.com/ytc/AKedOLQDR06gp26jxNNXh88Hhv1o-pNrnlKrYruqUIOx=s800-c-k-c0x00ffffff-no-rj",
"published_at":"2020-04-13T03:51:15.590Z",
"twitter_link":"yukihanalamy",
"view_count":66576847,
"subscriber_count":813000,
"video_count":430
}
},
{
"id":203019193,
"yt_video_key":"QM2DjVNl1gY",
"bb_video_id":"None",
"title":"【MINECRAFT】 Adventuring with Mumei! #holoCouncil",
"thumbnail":"None",
"status":"live",
"live_schedule":"2021-09-14T02:00:00.000Z",
"live_start":"2021-09-14T02:00:58.000Z",
"live_end":"None",
"live_viewers":8600,
"channel":{
"id":2260365,
"yt_channel_id":"UCO_aKKYxn4tvrqPjcTzZ6EQ",
"bb_space_id":"None",
"name":"Ceres Fauna Ch. hololive-EN",
"description":"A member of the Council and the Keeper of \"Nature,\" the second concept created by the Gods.\nShe has materialized in the mortal realm as a druid in a bid to save nature.\nShe has Kirin blood flowing in her veins, and horns that are made out of the branches of a certain tree; they are NOT deer antlers.\n\n\"Nature\" refers to all organic matter on the planet except mankind.\nIt is long said that her whispers, as an avatar of Mother Nature, have healing properties. Whether or not that is true is something only those who have heard them can say.\nWhile she is usually affable, warm, and slightly mischievous, any who anger her will bear the full brunt of Nature\\'s fury.\n\n",
"photo":"https://yt3.ggpht.com/0lkccaVapSr1Z3uuXWbnaQxeqRWr9Tcs4R9rLBRSrAsN9gLacpiT2OFWfFKr4NhF97_hqK3eTg=s800-c-k-c0x00ffffff-no-rj",
"published_at":"2021-07-26T15:38:58.797Z",
"twitter_link":"ceresfauna",
"view_count":5003954,
"subscriber_count":253000,
"video_count":17
}
}
],
My code:
url = "https://api.holotools.app/v1/live"
response = urlopen(url)
data_json = json.loads(response.read())
print(data_json['live'])
I think you're new to programming language so following is the special note for the new programmer.
You did well in printing the data but this is not end because your
goal is to get the name so you need to traverse in the response
one by one let me show you
url = "https://api.holotools.app/v1/live"
response = urlopen(url)
data_json = json.loads(response.read())
dicts = data_json['live']
#Why I'm using loop here? Because we need to get every element of list(data_json['live'] is a list)
for dict in dicts:
print(dict["channel"]["name"]
***Now here after getting single element from list as a dict I select its key which is "channel"***
Following are some useful links through which you can learn how to traverse in json
https://www.kite.com/python/answers/how-to-iterate-through-a-json-string-in-python
https://www.delftstack.com/howto/python/iterate-through-json-python/
There are also stackoverflow answer which are about: How to get data from json? but it need some programming skills too following is the link of answers.
Iterating through a JSON object
Looping through a JSON array in Python
How can I loop over entries in JSON?

How to access the tweepy entities expanded_url and why some are not available as object properties

I'm trying to get my head around tweepy and extracting data about followers in particular.
I'm authenticated, queried twitter for details of my own followers and can print out details about them using
Followers = AboutMe.followers
for follows in Followers():
print(follows.id, "is user ID for ", follows.screen_name, " from ", follows.location, follows.url)
When I execute that I get urls like https://t.co/[uniquestring] instead of FQDMs which I was hoping for
There is a property/entity called expanded_url but its not accessible as a object property. Why is that? and how do I access it if its embedded in lower levels of json entities
I provide a sample of the output if I print(follows.entities)
{'url': {'urls': [{'url': 'https://t.co/[string]', 'expanded_url':
'http://www.fqdm', 'display_url': 'domain.tld', 'indices': [0, 23]}]},
'description': {'urls': []}}
As per the documentation and the output of print(follows.entities) the following code answers your question to get FQDN for followers:
Followers = AboutMe.followers
for follows in Followers():
print(follows.id, "is user ID for ", follows.screen_name, " from ", follows.location, follows.entities.url.urls[0].expanded_url)
You might also want to handle the case when user has no url.

Google books api returns missing parameters

I am making a react app that searches for a book by title and returns the results.
It's mostly working fine, but for some titles searched (such as "hello") it can't get the results because the parameters are missing.
Specially, the "amount" value is missing, and it can get me e-books that are not for sale even if I add the filter=paid-ebooks param while fetching the api. Using projection=full doesn't help either.
For example, when I call the api with
https://www.googleapis.com/books/v1/volumes?printType=books&filter=paid-ebooks&key=${APIKEY}
and use the fetched data inside books array in reactjs:
this.props.books.map((book, index) => {
return (
<CardItem
key={index}
title={book.volumeInfo.title}
authors={book.volumeInfo.authors ?
book.volumeInfo.authors.join(', ') :
"Not provided"}
price={book.saleInfo.listPrice.amount}
publisher={book.volumeInfo.publisher}
addToCart={() =>
this.props.addItem(this.props.books[index])}
/>
)
})
One of the results it gets is like this:
"saleInfo": {
"country": "TR",
"saleability": "NOT_FOR_SALE",
"isEbook": false
}
While it should be like, what's expected is :
"saleInfo": {
"country": "TR",
"saleability": "FOR_SALE",
"isEbook": true,
"listPrice": {
"amount": 17.23,
"currencyCode": "TRY"
}
And trying to search with this api answer throws the error :
TypeError: Cannot read property 'amount' of undefined
price={book.saleInfo.listPrice.amount}
As you can see in react code's authors, this issue comes up with authors parameter too, which I've bypassed as seen in the code. But I cannot do the same with amount. Is this a known error in Google Books API or is there a way to prevent this? I don't understand why it still returns me e-books that are not for sale even with filter=paid-ebooks param.
I have not dug into the API documentation. An ideal solution would be a query param that only sends back books with a list price (like you tried with filter=paid-ebooks). Because that's not working, a simple fix would be to filter your results once you get them.
Assuming the response contains an array of book objects, it would look something like this:
const paidBooks = apiResponse.data.filter(book => book.listPrice)
This code will take the response from the API, and filter out all books that do not contain a truthy value for listPrice
That totally right, actually i never used react but the same logic try using try{ }catch(error){} for those missing data

Microsoft Graph update SharePoint list item multi choice field

What is the proper JSON syntax to update a multi-choice list item field using the Microsoft Graph?
Multi choice fields return a json array of strings like:
GET: /v1.0/sites/{siteId}/lists/{listId}/items/{itemId}
"CAG_x0020_Process_x0020_Status": [
"Proposed Funding - Customer Billed",
"Proposed Funding - Sales Funded",
"SOW - Needed"
]
However, when using the same syntax to update the field a 400 invalid request is returned.
PATCH: /v1.0/sites/{siteId}/lists/{listId}/items/{itemId}/fields
"CAG_x0020_Process_x0020_Status": [
"Proposed Funding - Customer Billed",
"Proposed Funding - Sales Funded",
"SOW - Needed"
]
Error returned:
{
"error": {
"code": "invalidRequest",
"message": "The request is malformed or incorrect.",
"innerError": {
"request-id": "2251e25f-e4ce-491f-beb9-e463c7d8d5af",
"date": "2018-05-16T15:16:23"
}
}
}
I am able to update all other fields requested, but this last field is holding up a release of the application.
To elaborate on what #muhammad-obaidullah-ather wrote in the comments, for string multiple choices you need to define the type as Collection(Edm.String) and then his solutions works for me. Repeating what he wrote as complete answer.
This should be sent as a PATCH like this:
PATCH /v1.0/sites/{SiteId}/lists/{ListId}/items/{ItemId}/fields
{"*FieldName*#odata.type":"Collection(Edm.String)","*FieldName*":["*Value1*","*Value2*"]}
This works for me
graph.api(url)
.version('beta')
.post({
'fields': {
'AssignedToLookupId#odata.type': 'Collection(Edm.Int32)',
'AssignedToLookupId': [5,13]
}
});
Unfortunately, a number of column types, including MultiChoice, cannot be updated via Microsoft Graph today. I would recommend adding this to the Office Dev UserVoice so it remains on the radar of the SharePoint/Graph team.

REST POST json body to support complex query advice

I'm fairly new to REST. All of our legacy webservices were SOAP based with enterprise (ORACLE or DB2) databases. We are now moving to REST/couchbase.
Our team is looking into implementing a complex query method. We already have implemented simple query methods using GET, for example GET returns all entries and a GET/067e6162-3b6f-4ae2-a171-2470b63dff00 would return the entry for 067e6162-3b6f-4ae2-a171-2470b63dff00.
We want to support a query method that would support receiving several query parameters such a list of Ids and date ranges. The number of Ids can number into a few thousand and because of this, we realize we cannot pass these query parameters in a GET HTTP header since there is a limit on header size.
We are starting to look into passing our query parameters into the JSON body of a POST request. For example, we could have client pass in a few thousand Ids as an array and also pass in a date range, so we'd have each query param/filter be an object. The JSON body would then be an array of objects. For example:
{
"action" : "search",
"queryParameters" : {
[
{
“operation”: “in”,
"key" : "name.of.attribute.Id",
"value" : "[{ "id: "067e6162-3b6f-4ae2-a171-2470b63dff00"}, {"id": "next id"....}],
},
{
“operation”: “greater”,
"key" : "name.of.attribute “,
"value" : "8/20/2016"
},
{
“operation”: “less”,
"key" : "name.of.attribute “,
"value" : "8/31/2016"
}
]
}
The back end code would then receive POST and read the body. It would see action is a search and then look for any entries in the list that are in the list of Ids that are in the date range of > 8/20/2016 and < 8/31/2016.
I've been trying to look online for tips/best practices on how best to structure the JSON body for complex queries but have not found much. So any tips, guidance or advice would be greatly appreciated.
thanks.