I have the following text structure in JSON:
{
"Results":{
"Burger King":{
"Location":"New York",
"Address":"Avenue Dalmatas, 20"
},
"Mcdonalds":{
"Location":"Los Angeles",
"Address":"Oscar Street, 50"
}
}
}
I managed to get the city and address results, but for that I need to mention the name of the restaurant in the code to grab the token string.
Dim JSON As String = **json here**
Dim token As JToken
token = JObject.Parse(JSON.ToString())
Dim data = token.SelectToken("Results").SelectToken("Burger King").SelectToken("Location")
My question is, how can I list only the restaurants (Burger King, Mcdonalds, etc), for example, in a Listbox? So I can add some feature that checks the address and city with the user's choice, which I know and already understand how to do, but getting the token with only the names of the restaurants is being difficult for me. If i have a new restaurant name for example, I wouldn't want to include manually in the code. I have tried a lot of different ways, but the last one I have used it was the following:
Dim data = token.SelectToken("Results").SelectToken(0) 'i thought it would print 'Burger King'
'or this one
Dim data = token.SelectToken("Results")(0).ToString()
I've tried some 'For Each' loop code but I wasn't successful either. I've researched countless methods on how to do this and nothing works. I believe it's something simple that I'm either ignoring or completely forgetting.. Please give me a light! Thanks.
I can post c# code for you, it would be easier for you to translate it to VB if you need
var jsonObject= JObject.Parse(json);
List<string> restaurantNames= ((JObject)jsonObject["Results"]).Properties()
.Select(x=>x.Name).Distinct().ToList();
result
Burger King
Mcdonalds
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?
Hi I am quite new to VBA and JSON. I want to parse a JSON script using a VBA macro.
I already have an Excel table with each field and it's corresponding JSON path.
While trying to pick the value from Excel table, it is read as string and, quotes are added in the beginning and end of the string. The quotes " in the beginning and the end of the path of the JSON variable makes it impossible to read the value from the JSON script.
For example, if the path is project->name, the location in Excel table is ("project")("name"). But after reading it in VBA it becomes "("project")("name")". With the extra quotes " in the path, the location is not getting identified in the VBA code.
{
"quiz": {
"sport": {
"name": "Basketball",
"Questions":{
"question1": "Which one is correct team name in NBA?",
"question2":"Who is your favorite player",}
}
}
}
For this JSON script, I have created an Excel table with paths of question1 and question2:
("quiz")("sport")("name")("question1")
("quiz")("sport")("name")("question2")
The following code runs a loop and identify path of question1 first and returns "Which one is correct team name in NBA?" and do the same for question2.
But, item(path) is returning an empty string while writing the path completely in the code returns the correct value.
Set jsonObject = JsonConverter.ParseJson(JsonScript) 'Parse Json from GitHub
For Each item In jsonObject("data")
For i = 1 To nrow ' loops through rows with path for each field
Path = ws2.Range("C" & i).Value 'path of each field
MsgBox item(Path) 'returns Empty
question1 = item("quiz")("sport")("name")("question1") 'returns question1 value:Which one is correct team name in NBA?
Next
Next
You can't apply in that way particularly with the (). You can have the paths, as a comma separated list of path elements (no spaces), in the sheet and do the following.
You also need to remove the additional "," after player.
Note: I am testing the UBound of the array generated by the split on the "," of the string read in from the sheet and held in the array (arr) at the current index i. This ensures I apply the write nested syntax to retrieve the required value.
I am not sure where you are getting "data" from. I can't see it in the string provided. You would amend according to your actual JSON if different.
Data:
Output:
VBA:
Option Explicit
Public Sub GetInfoFromSheet()
Dim json As Object, jsonSource As String, paths(), i As Long, ws As Worksheet, arr() As String
Set ws = ThisWorkbook.Worksheets("Sheet1")
jsonSource = ws.[C1]
Set json = JsonConverter.ParseJson(jsonSource)
paths = Application.Transpose(ws.Range("A1:A3").Value)
For i = LBound(paths) To UBound(paths)
arr = Split(paths(i), ",")
Select Case UBound(arr)
Case 2
Debug.Print json(arr(0))(arr(1))(arr(2))
Case 3
Debug.Print json(arr(0))(arr(1))(arr(2))(arr(3))
End Select
Next i
End Sub
JSON string in C1:
{ "quiz": { "sport": { "name": "Basketball", "Questions":{ "question1": "Which one is correct team name in NBA?", "question2":"Who is your favorite player"} } } }
Im new to angularJS and web designing as a whole. Im trying to get a data field(or element) from a JSON. For example, this is what the JSON looks like
{
"Name":"Raymond Eugene Monce",
"Dateofbirth":"1924-0308T00:00:00Z",
"Ethnicity":"Caucasian",
"Languages":["{English}"],
},
and I'm trying to get the "Name" data field. This is what my .js file looks like,
var profile = angular.module('profile', ['ui.bootstrap','ngResource']);
profile.controller("profileController", ["$scope","$resource", function($scope, $resource) {
// get the user id
$scope.userid = sessionStorage["cerestiuserid"];
// json we get from server
$scope.apicall = sessionStorage["cerestihome"]; // NEED TO CHANGE API
// grabs the user we want
$scope.userResource = $resource($scope.apicall + "/api/userprofile/",
{Userid:21},
{'get':{method: 'POST'}}
);
// fetch JSON
$scope.userResource.get(function(result) {
// get the name field
$scope.name = result;
sessionStorage["name"] = JSON.stringify(result);
});
and my .html file,
<div ng-controller = "profileController" style="float:left">
<!-- profile pic -->
<div class="pull-left">
<div class="container-fluid">
<div class="profile">
<div class="row">
<div class="center-block">
<div class="profilePic">
<img ng-src="{{profilePic()}}" class="img-responsive">
<!-- name field -->
<label class="caption">
<h4>{{name.name}}</h4>
</label>
</div>
Again, Im not having problems with the Database or API calls. I just want to know how I can get and display the name field of the JSON. Thanks.
strelok2010's comment above should work although that depends on if your result really looks like the one defined at the top of your question.
Your result seems to be a normal javascript object not JSON. (yeah they are different, and that confused me when I learned it.) I assume that because you stringify the result from a javascript object into JSON. Therefore if that is working right your result is either a javascript object or an array of javascript objects. I'm assuming an array. You might want to check though.
I noticed your earlier post had a related problem.
In that one you were asking to access a property of an object that was in an array. In that case it was result as well. Here was the answer from your previous question
var result = [{"name": "Jason"
"date of birth": "february 23, 2985"
....
}];
var firstResultsName = result[0].name;
There are two things I am unsure of due to the inconsistency between this and your last question.
First your name property in your results object is spelled with a capital N here as opposed to a lower case n in your last question.
Keep in mind that capitilization matters in javascript.
Second your result in your last question was an array of objects and in this it seems to be just an object.
So depending on which one it is will determine your solution. So instead of writing every possible solution I'll show you how to determine the solution.
Remember we are dealing with a normal array of javascript objects. I'll try to go into detail so it's extra clear (sorry I heard you were new to web developement, I'm assuming JavaScript too.), but sorry if it's a little too detailed. I will also be breaking it into parts to go deeper into the array of objects that I'll use in my example, but traversing into the data structure can all be done in a single line as I will show.
You can only do actions on the 'outermost-form' (by the way 'outermost-form' is just a term I'll use for clarification it's not really a technical term.) and work your way into the collection (object/array/string)
As an example we have an array of people, with the array being the 'outermost-form'
var people = [
{
"name": "Bob",
"occupation": "Architect",
"date of birth": "01/23/83"
},
{
"name": "Timothy",
"Occupation": "Accountant",
"date of birth": "02/23/78"
}
];
If we saw the value of people at this moment it not surprisingly be.
[
{
"name": "Bob",
"occupation": "Architect",
"date of birth": "01/23/83"
},
{
"name": "Timothy",
"Occupation": "Accountant",
"date of birth": "02/23/78"
}
]
Start with the Array
Since it's an array as the 'outermost-form' we can get one of its values using an index. Just like any other array. Just for a bit of contrast I'll show you how what we are doing is similar to any other array by showing an example of an array by itself
// simple array example
var array = ["foo", "bar", "baz"];
array[0] // returns "foo"
// more simple array example, but less practical (it's more just for showing how javascript can work.)
["foo", "bar", "baz"][2] // returns "baz"
Back to our main example. Let's make a variable person and store our first person in the people array in that value.
var person = people[0];
Now if saw our person variable it would equal the following
{
"name": "Bob",
"occupation": "Architect",
"date of birth": "01/23/83"
}
You can see just like the normal array it grabs the first item in the array. You can see how we are slowly traversing into our people data structure. (that being an array of objects.)
Enter the Object
Okay so now we have the person object, but we want the name of that person so since we are dealing with an object we have to access its properties we can do this with either 'dot notation', e.g. <object>.<property>, or 'bracket notation' which can be done with either a variable or a string for the property name. e.g. <object>.["<property>"] or <object>.[<variable>]
So just as a side example I will show you what it normally takes to get the value of a property of an object just so you can compare and see there's no 'magic' going on. Keep in mind javascript is case-sensitive. Also javascript objects properties can go with or without surrounding quotes unlike JSON. One last thing having a space in the property name forces us to use quotes, and also forces us to access that property via bracket notation.
var result;
var obj = { foo: 1, Bar: 2, "foo bar": 3 };
var randomVarName = "Bar"; // notice the capital B in Bar is important since it was declared that way.
result = obj.foo; // result equals 1
result = obj[randomVarName]; // result equals 2
result = obj["foo bar"]; // result equals 3
Back again to our main train of thought. So we have traversed into our people array to find the person object now let's get their name.
var name = person.name;
The value of name would be.
"Bob"
You can do with that what you wish. You could have also used any of the previous ways to get an objects property including bracket notation.
Do Everything we just did in a Single Line
So to write that all in one line you would just write
people[0].name
Apply to your Question
So to apply to your question if your result looks like this
var result = [
{
"name": "Jason"
"date of birth": "february 23, 2985"
....
}
];
Then you need this to get the name
result[0].name
If it's just this
var result = {
"name": "Jason"
"date of birth": "february 23, 2985"
....
}
Then you just need
result.name
As asked in the comment if you want to get the date of birth property out of the object you need to use bracket notation to get the element out of an object. Bracket notation is one of the two object property accessors the other being dot notation. I covered both at the enter the object section. It can be used at anytime, but is usable in some cases that dot notation does not work.
An example and quote from MDN:
get = object[property_name];
object[property_name] = set;
property_name is a string. The string does not have to be a valid identifier; > it can have any value, e.g. "1foo", "!bar!", or even " " (a space).
So since certain character like spaces can't be used in dot notation bracket notation must be used in those special cases when those characters are present.
Below is the bracket notation of the date of birth.
result["date of birth"]
Like I said before it can be used anywhere, but generally dot notation is preferred for its brevity. So just to show that, we will show the name field being accessed using bracket notation:
result["name"]
One additional reason you may want to use bracket notation is for its ability to use variables like so.
var prop_name = "date of birth";
result[prop_name];
which actually if you understand the principle of that example the MDN example might make more sense.
If you have a question feel free to leave me a comment.
"divisions":{
"ocd-division/country:us/state:co/place:aurora":{
"name":"Aurora city",
"scope":"citywide",
"officeIds":[
"O0",
"O1"]
}}
I am using Google Civic Information API to get representive information. let's say this is a part of JSON generated by Google and I want to access its elements but the issue is - i cant use "ocd-division/country:us/state:co/place:aurora" as a key, because its dynamically generated by Google.
If I search for some different address like India, the key will be different from "ocd-division/country:us/state:co/place:aurora" to something else(instead of 'us', there would be 'in'), So please suggest the way I should access in this case the value.
Please clarify if you don't understand question or need more clarification.
Parse the json to a hash:
parsed_data = JSON.parse google_data
then either iterate over all divisions:
parsed_data['divisions'].each do |division_key, division_info|
# do something with each division
end
or get only the first one:
division_key, division_info = parsed_data['divisions'].first
Use this if you want parse the key as well:
more_info = division_key.split('/').inject(Hash.new) do |hash, key_part|
if key_part.include? ":"
key, value = key_part.split ":"
hash[key] = value
end
hash
end
Now you can access it via more_info['country']
I have a json string: {"jsonrpc":"2.0","result":[{"event":{"id":"27151641","name":"TSW Pegasus FC (Res) v Sun Hei SC (Res)","countryCode":"HK","timezone":"GMT","openDate":"2014-02-19T12:30:00.000Z"},"marketCount":14},{"event":{"id ":"27151646","name":"Humble Lions v Boys Town FC... etc etc
So the result bit is a list of event/marketcount pairs. I've used the parse method in a class module called jsonlib which I got from http://code.google.com/p/vba-json/issues/attachmentText?id=15&aid=150001000&name=jsonlib.cls&token=31ObtlGBtaGXd2KR0QLyffX_x8Y:1359742317106
This creates an object (jason_obj) which represents the result bit above. Now I want to get a list of ids for each event. I can use the for each ... construct to return each event/marketcount pair as an object, but I can't work out how to get to the id field that is somewhere in the event object. I tried to use the tostring method to get a clue, and from that this code should work but it doesn't:
For Each eventItem In jason_obj
this_eventx = eventItem("event")
this_id = this_eventx("id")
Next
Don't know much about accessing objects/collections. Can anyone help? Thanks
Objects need to be set and references should use item:
For Each eventItem In jason_obj
set this_eventx = eventItem.item("event")
this_id = this_eventx.item("id")
Next
HTH
Yes it did