I am trying to extract some info using the wikipedia api - http://en.wikipedia.org/w/api.php?action=query&generator=random&grnnamespace=0&prop=extracts&explaintext&exintro=&format=json
The response I get is as below,
{"query":
{"pages":
{"1350786":
{"pageid":1350786,"ns":0,"title":"2005 in Wales","extract":"This article is about the particular significance of the year 2005 to Wales and its people."}}}}
How can I traverse to the "extract" field here in node.js? I am trying to use query.pages. something but since the id changes for each call I make, I am not sure how to access the extract.
If you don't know the id (which is a dictionary key under pages) you can just traverse all the keys under pages to get the extract field:
var obj1 =
{
"query":
{
"pages":
{"1350786":
{"pageid":1350786,"ns":0,"title":"2005 in Wales",
"extract":"This article is about the particular significance of the year 2005 to Wales and its people."}
}
}
}
for (var key in obj1.query.pages){
console.log(obj1.query.pages[key].extract);
}
Related
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?
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.
I'm trying to use OpenSearchServer in one of my applications using RestFul JSON API .Can you please provide an example for querying search between 2 dates using the restful JSON api?
Below is my code so far
{"query":"test help","rows":100,
"returnedFields":[
"fileName",
"url"
]
}
Sorry for the bandwidth wastage.
To search between two dates using JSON API, we can use the "Relative date filter " .
Here's what the documentation says :
The Relative date filter can be used for this. Let's say that documents are indexed with the current date in the field indexedDate. In our example the date is expressed using the yyyyMMddHHmmss format - for instance 20141225130512 stands for the 25th of December, 2014, at 1:05:12 PM.
eg:
"filters":[
{
"negative":false,
"type":"RelativeDateFilter",
"from":{
"unit":"days",
"interval":2
},
"to":{
"unit":"days",
"interval":0
},
"field":"indexedDate",
"dateFormat":"yyyyMMddHHmmss"
}
],
Further details can be found here :http://www.opensearchserver.com/documentation/faq/querying/how_to_use_filters_on_query.md
I have this JSON output
{
"status":1,
"complete":1,
"list":{
"792489954":{
"item_id":"792489954",
"resolved_id":"792489954",
"given_url":"http:\/\/www.liveathos.com\/?gclid=Cj0KEQiAzb-kBRDe49qh9s75m-wBEiQATOxgwZcJ5_ws34o4PUSUYDGqs8HEbLF-LyjxrTPOwn6AYV8aAmMk8P8HAQ",
"given_title":"Athos - Wearable Technology for Fitness",
"favorite":"0",
"status":"0",
"time_added":"1418754744",
"time_updated":"1418754746",
"time_read":"0",
"time_favorited":"0",
"sort_id":0,
"resolved_title":"Wearable Technology for Fitness",
"resolved_url":"http:\/\/www.liveathos.com\/?gclid=Cj0KEQiAzb-kBRDe49qh9s75m-wBEiQATOxgwZcJ5_ws34o4PUSUYDGqs8HEbLF-LyjxrTPOwn6AYV8aAmMk8P8HAQ",
"excerpt":"Thank you for reserving Athos. You will receive a confirmation email with reservation details and a referral link where you get $10 off your next order.",
"is_article":"0",
"is_index":"0",
"has_video":"0",
"has_image":"0",
"word_count":"25"
},
"692647226":{
"item_id":"692647226",
"resolved_id":"692647226",
"given_url":"http:\/\/www.terrafugia.com\/news",
"given_title":"News | Terrafugia",
"favorite":"0",
"status":"0",
"time_added":"1418754204",
"time_updated":"1418754204",
"time_read":"0",
"time_favorited":"0",
"sort_id":1,
"resolved_title":"News",
"resolved_url":"http:\/\/www.terrafugia.com\/news",
"excerpt":"",
"is_article":"0",
"is_index":"1",
"has_video":"0",
"has_image":"0",
"word_count":"0"
},
`...etc` "since":1419641101
};
It's a JSON with a list that should have article items on it. I want to access the properties of these smaller items like given_url.
I'm using
for key in (BIGJSONRESPONSE).list
do etc...
When I try printing the key, I get only the id that comes before an item. Any idea how to access more?
Thanks!
You asked for the keys, you got the keys. To get the item associated with that key, use BIGJSONRESPONSE.list[key].
This should be correct:
for in returns the keys of an object. Since the key refers to a property of the object one can access the property using [key].
for (key in (BIGJSONRESPONSE).list)
{
console.log(BIGJSONRESPONSE.list[key]) // log the entry to console for debugger.
}
I'm using Postman to make REST API calls to a server. I want to make the name field dynamic so I can run the request with a unique name every time.
{
"location":
{
"name": "Testuser2", // this should be unique, eg. Testuser3, Testuser4, etc
"branding_domain_id": "52f9f8e2-72b7-0029-2dfa-84729e59dfee",
"parent_id": "52f9f8e2-731f-b2e1-2dfa-e901218d03d9"
}
}
In Postman you want to use Dynamic Variables.
The JSON you post would look like this:
{
"location":
{
"name": "{{$guid}}",
"branding_domain_id": "52f9f8e2-72b7-0029-2dfa-84729e59dfee",
"parent_id": "52f9f8e2-731f-b2e1-2dfa-e901218d03d9"
}
}
Note that this will give you a GUID (you also have the option to use ints or timestamps) and I'm not currently aware of a way to inject strings (say, from a test file or a data generation utility).
In Postman you can pass random integer which ranges from 0 to 1000, in your data you can use it as
{
"location":
{
"name": "Testuser{{$randomInt}}",
"branding_domain_id": "52f9f8e2-72b7-0029-2dfa-84729e59dfee",
"parent_id": "52f9f8e2-731f-b2e1-2dfa-e901218d03d9"
}
}
Just my 5 cents to this matter. When using randomInt there is always a chance that the number might eventually be present in the DB which can cause issues.
Solution (for me at least) is to use $timestamp instead.
Example:
{
"username": "test{{$timestamp}}",
"password": "test"
}
For anyone who's about to downvote me this post was made before the discussion in comments with the OP (see below). I'm leaving it in place so the comment from the OP which eventually described what he needs isn't removed from the question.
From what I understand you're looking for, here's a basic solution. It's assuming that:
you're developing some kind of script where you need test data
the name field should be unique each time it's run
If your question was more specific then I'd be able to give you a more specific answer, but this is the best I can do from what's there right now.
var counter = location.hash ? parseInt(location.hash.slice(1)) : 1; // get a unique counter from the URL
var unique_name = 'Testuser' + counter; // create a unique name
location.hash = ++counter; // increase the counter by 1
You can forcibly change the counter by looking in the address bar and changing the URL from ending in #1 to #5, etc.
You can then use the variable name when you build your object:
var location = {
name: unique_name,
branding_domain_id: 'however-you-currently-get-it',
parent_id: 'however-you-currently-get-it'
};
Add the below text in pre-req:
var myUUID = require('uuid').v4();
pm.environment.set('myUUID', myUUID);
and use the myUUID wherever you want
like
name: "{{myUUID}}"
It will generate a random unique GUID for every request
var uuid = require('uuid');
pm.globals.set('unique_name', 'testuser' + uuid.v4());
add above code to the pre-request tab.
this was you can reuse the unique name for subsequent api calls.
Dynamic variable like randomInt, or guid is dynamic ie : you donot know what was send in the request. there is no way to refer it again, unless it is send back in response. even if you store it in a variable,it will still be dynamic
another way is :
var allowed = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
var shuffled_unique_str = allowed.split('').sort(function(){return 0.5-Math.random()}).join('');
courtsey refer this link for more options