I am having the following json which I am reading from an url:-
{
"body": [
{
"id": "1",
"name": "John Doe",
"email": "johndoe#gmail.com",
"designation": "Data Scientist",
"created": "2012-06-01 02:12:30"
},
{
"id": "2",
"name": "David Costa",
"email": "sam.mraz1996#yahoo.com",
"designation": "Apparel Patternmaker",
"created": "2013-03-03 01:20:10"
},
{
"id": "3",
"name": "Todd Martell",
"email": "liliane_hirt#gmail.com",
"designation": "Accountant",
"created": "2014-09-20 03:10:25"
},
{
"id": "4",
"name": "Adela Marion",
"email": "michael2004#yahoo.com",
"designation": "Shipping Manager",
"created": "2015-04-11 04:11:12"
},
{
"id": "5",
"name": "Matthew Popp",
"email": "krystel_wol7#gmail.com",
"designation": "Chief Sustainability Officer",
"created": "2016-01-04 05:20:30"
},
{
"id": "6",
"name": "Alan Wallin",
"email": "neva_gutman10#hotmail.com",
"designation": "Chemical Technician",
"created": "2017-01-10 06:40:10"
},
{
"id": "7",
"name": "Joyce Hinze",
"email": "davonte.maye#yahoo.com",
"designation": "Transportation Planner",
"created": "2017-05-02 02:20:30"
},
{
"id": "8",
"name": "Donna Andrews",
"email": "joesph.quitz#yahoo.com",
"designation": "Wind Energy Engineer",
"created": "2018-01-04 05:15:35"
},
{
"id": "9",
"name": "Andrew Best",
"email": "jeramie_roh#hotmail.com",
"designation": "Geneticist",
"created": "2019-01-02 02:20:30"
},
{
"id": "10",
"name": "Joel Ogle",
"email": "summer_shanah#hotmail.com",
"designation": "Space Sciences Teacher",
"created": "2020-02-01 06:22:50"
}
]
}
I am using the following vb.net code to read the above mentioned json and it is working fine.
Dim request As HttpWebRequest
Dim response As HttpWebResponse = Nothing
Dim reader As StreamReader
request = DirectCast(WebRequest.Create("http://../read.php"), HttpWebRequest)
response = DirectCast(request.GetResponse(), HttpWebResponse)
reader = New StreamReader(response.GetResponseStream())
Dim rawresp As String
rawresp = reader.ReadToEnd()
TextBox2.Text = rawresp
My question is, how I can read any child node (for example:"name")?
I have also tried the following code to read child node, but it is not working:-
Try
Dim jss As New JavaScriptSerializer()
Dim dict As Dictionary(Of String, String) = jss.Deserialize(Of Dictionary(Of String, String))(rawresp)
s = dict("body.name")
TextBox2.Text = s
Catch ex As Exception
End Try
Please help.
Thanks.
Related
Need help on parsing JSON data using VBA-Web tool (https://github.com/VBA-tools/VBA-Web) & VBA-JSON Converter
Here is my sample code that I am able to pull the order using the get method but I stumped on parsing the JSON to get the key, value pair that I want
Sub TestWC()
Dim WoocommerceClient As New WebClient
Dim Client As String
Dim Secret As String
WoocommerceClient.BaseUrl = "https://www.example.com"
Client = "ck"
Secret = "cs"
Dim Request As New WebRequest
Request.Method = Httpget
Request.AddQuerystringParam "consumer_key", Client
Request.AddQuerystringParam "consumer_secret", Secret
Dim Response As WebResponse
Request.Resource = "/wp-json/wc/v3/orders"
Set Response = WoocommerceClient.Execute(Request)
//Response.Data -> Should be equal to the JSON data
Dim test As Object
Set test = JsonConverter.ParseJson(Response.Data)
End Sub
When I run this code it will have a error popup saying object required 424 . I also did another work around where I put into the first cell the whole JSON Data using Sheet1.Range("A1").Value = Response.Content then by pulling the data from the cell into the function
Set test = JsonConverter.ParseJson(Sheet1.Range("A1").Value)
I still get the object required error, here is a Sample JSON format from Woocommerce REST API
"id": 727,
"parent_id": 0,
"number": "727",
"order_key": "wc_order_58d2d042d1d",
"created_via": "rest-api",
"version": "3.0.0",
"status": "processing",
"currency": "USD",
"date_created": "2017-03-22T16:28:02",
"date_created_gmt": "2017-03-22T19:28:02",
"date_modified": "2017-03-22T16:28:08",
"date_modified_gmt": "2017-03-22T19:28:08",
"discount_total": "0.00",
"discount_tax": "0.00",
"shipping_total": "10.00",
"shipping_tax": "0.00",
"cart_tax": "1.35",
"total": "29.35",
"total_tax": "1.35",
"prices_include_tax": false,
"customer_id": 0,
"customer_ip_address": "",
"customer_user_agent": "",
"customer_note": "",
"billing": {
"first_name": "John",
"last_name": "Doe",
"company": "",
"address_1": "969 Market",
"address_2": "",
"city": "San Francisco",
"state": "CA",
"postcode": "94103",
"country": "US",
"email": "john.doe#example.com",
"phone": "(555) 555-5555"
},
"shipping": {
"first_name": "John",
"last_name": "Doe",
"company": "",
"address_1": "969 Market",
"address_2": "",
"city": "San Francisco",
"state": "CA",
"postcode": "94103",
"country": "US"
},
"payment_method": "bacs",
"payment_method_title": "Direct Bank Transfer",
"transaction_id": "",
"date_paid": "2017-03-22T16:28:08",
"date_paid_gmt": "2017-03-22T19:28:08",
"date_completed": null,
"date_completed_gmt": null,
"cart_hash": "",
"meta_data": [
{
"id": 13106,
"key": "_download_permissions_granted",
"value": "yes"
}
],
"line_items": [
{
"id": 315,
"name": "Woo Single #1",
"product_id": 93,
"variation_id": 0,
"quantity": 2,
"tax_class": "",
"subtotal": "6.00",
"subtotal_tax": "0.45",
"total": "6.00",
"total_tax": "0.45",
"taxes": [
{
"id": 75,
"total": "0.45",
"subtotal": "0.45"
}
],
"meta_data": [],
"sku": "",
"price": 3
},
{
"id": 316,
"name": "Ship Your Idea – Color: Black, Size: M Test",
"product_id": 22,
"variation_id": 23,
"quantity": 1,
"tax_class": "",
"subtotal": "12.00",
"subtotal_tax": "0.90",
"total": "12.00",
"total_tax": "0.90",
"taxes": [
{
"id": 75,
"total": "0.9",
"subtotal": "0.9"
}
],
"meta_data": [
{
"id": 2095,
"key": "pa_color",
"value": "black"
},
{
"id": 2096,
"key": "size",
"value": "M Test"
}
],
"sku": "Bar3",
"price": 12
}
],
"tax_lines": [
{
"id": 318,
"rate_code": "US-CA-STATE TAX",
"rate_id": 75,
"label": "State Tax",
"compound": false,
"tax_total": "1.35",
"shipping_tax_total": "0.00",
"meta_data": []
}
],
"shipping_lines": [
{
"id": 317,
"method_title": "Flat Rate",
"method_id": "flat_rate",
"total": "10.00",
"total_tax": "0.00",
"taxes": [],
"meta_data": []
}
],
"fee_lines": [],
"coupon_lines": [],
"refunds": [],
"_links": {
"self": [
{
"href": "https://example.com/wp-json/wc/v3/orders/727"
}
],
"collection": [
{
"href": "https://example.com/wp-json/wc/v3/orders"
}
]
}
}```
I'm building a windows application using vb.net to take a Json file that will be downloaded daily and parse it and enter the values into a SQL database. The only part I'm getting stuck on is being about to parse the Json data to get the values I need.
Public Sub json_parse(ByVal result_json As String)
Try
Dim json As String = result_json
Dim ser As JObject = JObject.Parse(json)
Dim data As List(Of JToken) = ser.Children().ToList
For Each item As JProperty In data
item.CreateReader()
Select Case item.Name
Case "data"
For Each msg As JObject In item.Values
MsgBox(msg.ToString)
Next
End Select
Next
Catch __unusedException1__ As Exception
'MsgBox(__unusedException1__.ToString)
End Try
End Sub
{
"data": {
"wsj_mdstrip_na,us": {
"set": 1562756496071,
"ttl": 300000,
"data": {
"id": "na,us",
"type": "wsj_mdstrip",
"data": [
{
"timeZone": "CDT",
"localTimeZoneTimestamp": "5:51 AM CDT 07/10/19",
"localTimestamp": "5:51 AM 07/10/19",
"etTimestamp": "6:51 AM ET 07/10/19",
"mdTimestamp": "2019-07-10T06:51:35-04:00",
"timestamp": "2019-07-10T05:51:35.365",
"chartingSymbol": "Future/US/XCBT/YM00",
"updatedTimestamp": "2019-07-10T07:01:36-04:00"
},
{
"deltaBarPosNeg": "deltaBar-neg",
"etTimestamp": "6:51 AM ET 07/10/19",
"chartingSymbol": "Future/US/XCME/ES00",
"pastCloses": [
{
"range": "P1Y",
"price": 2775.75
},
{
"range": "P3Y",
"price": 2145.75
}
]
}
]
}
},
"wsj_nav_na,us": {
"set": 1562754843231,
"ttl": 1800000,
"isStale": false
},
"mdc_cashprices_": {
"set": 1562756402351,
"ttl": 90000,
"data": {
"id": "{\"requestedCommodities\":\"all\",\"groupIntoMapBy\":\"type\",\"groupIntoSetsBy\":\"subType\"}",
"type": "mdc_cashprices",
"data": {
"instruments": [
{
"code": null,
"djShortName": "Gold-EnglehardFab",
"instrumentID": "511498",
"name": "Engelhard fabricated products",
"subType": "Gold, per troy oz",
"type": "Precious metals",
"ask": "-",
"bid": "-",
"last": "1500.72",
"previousDay": "1509.33",
"previousYear": "1351.58"
},
{
"code": null,
"djShortName": "Silver-EngelhrdFab",
"instrumentID": "511558",
"name": "Engelhard fabricated products",
"subType": "Silver, troy oz.",
"type": "Precious metals",
"ask": "-",
"bid": "-",
"last": "18.0600",
"previousDay": "18.0960",
"previousYear": "19.3200"
},
{
"code": null,
"djShortName": "SilverHandy&HarmB",
"instrumentID": "511560",
"name": "Handy & Harman base price",
"subType": "Silver, troy oz.",
"type": "Precious metals",
"ask": "-",
"bid": "-",
"last": "15.1070",
"previousDay": "15.0420",
"previousYear": "16.1000"
},
{
"code": null,
"djShortName": "Platinum-EngelhFab",
"instrumentID": "511554",
"name": "Platinum, Engelhard fabricated products",
"subType": "Other precious metals",
"type": "Precious metals",
"ask": "-",
"bid": "-",
"last": "912.0",
"previousDay": "914.0",
"previousYear": "946.0"
},
{
"code": null,
"djShortName": "Palladium-EngelInd",
"instrumentID": "511553",
"name": "Palladium, Engelhard industrial bullion",
"subType": "Other precious metals",
"type": "Precious metals",
"ask": "-",
"bid": "-",
"last": "1561.0",
"previousDay": "1573.0",
"previousYear": "955.0"
},
{
"code": null,
"djShortName": "Palladium-EngelFab",
"instrumentID": "511552",
"name": "Palladium, Engelhard fabricated products",
"subType": "Other precious metals",
"type": "Precious metals",
"ask": "-",
"bid": "-",
"last": "1661.0",
"previousDay": "1673.0",
"previousYear": "1055.0"
}
],
"timestamp": "7/09/19"
}
}
},
"consumer_corphat_corphat": {
"set": 1562756495973,
"ttl": 90000,
"data": {
"id": "corphat",
"type": "consumer_corphat",
"data": [
{
"ncLinks": [
{
"title": "Big Decisions",
"url": "http://www.bigdecisions.com/",
"nofollow": "false"
},
{
"title": "Business Spectator",
"url": "https://www.businessspectator.com.au/",
"nofollow": "false"
}
]
},
{
"djLinks": [
{
"title": "Barron's",
"url": "https://www.barrons.com",
"nofollow": "false"
},
{
"title": "BigCharts",
"url": "http://bigcharts.marketwatch.com",
"nofollow": "false"
}
]
}
]
},
"isStale": false
}
},
"currentState": {
"data": [
"0.0.3.0.0",
"0.0.3.1.0.0.2"
],
"components": {
"code___decoratedComponent___275181c7-8620-4df3-a008-d0cd9937db22___WSJTheme---WSJBase---WSJForms---WSJTables": {
"id": "275181c7-8620-4df3-a008-d0cd9937db22",
"decorators": [
"WSJTheme",
"WSJBase",
"WSJForms",
"WSJTables"
]
},
"code___decoratedComponent___c8882c9c-15d3-4d1f-9b0e-81b6f321365d___WSJTheme---WSJBase---WSJForms---WSJTables": {
"id": "c8882c9c-15d3-4d1f-9b0e-81b6f321365d",
"decorators": [
"WSJTheme",
"WSJBase",
"WSJForms",
"WSJTables"
]
}
}
}
}
I'm trying to get the values for "last", "previousDay" and "previousYear" from:
data > mdc_cashprices_ > data > instruments > (where djShortName = "Gold-EnglehardFab" and djShortName = "Silver-EngelhrdFab" and djShortName = "Platinum-EngelhFab" and djShortName = "Palladium-EngelFab")
I'm also trying to get the value for "timestamp" from:
data > mdc_cashprices_ > data > timestamp
In my current code I can only get to the 1st "data" tier.
Any help would be greatly appreciated.
Use something like https://jsonformatter.curiousconcept.com/ to view it more easily.
Then simply
Dim Something as JObject = JObject.Parse(<your JSON>)
Then get what you want with
Something1 = Something("data")("mdc_cashprices")("data")("data")("instruments")(0)("last") 'basically you just traverse the levels, you use the id/text for regular stuff (inside {}) and numbers for arrays (inside [])
Since it's an array you would probably want to loop it
For Each item In Something("data")("mdc_cashprices")("data")("data")("instruments")
Something2 = item("last")
Next
Btw there are some formatting issues here >>> mdc_cashprices_{\"req... <<< that _ and \ shouldn't be there"
I have serialized a json stream using Newtonsoft.Json.
Here is what the data looks like:
{
"id": "55115654340-8d43-440c-8683-c3aa299e39cd",
"timestamp": "2018-02-09T13:57:34.143Z",
"lang": "en",
"result": {
"source": "agent",
"resolvedQuery": "HELP",
"action": "",
"actionIncomplete": false,
"parameters": {},
"contexts": [],
"metadata": {
"intentId": "63b7b4a5-3f7f-41b1-81ec-fcc6f70fb173",
"webhookUsed": "true",
"webhookForSlotFillingUsed": "false",
"webhookResponseTime": 5000,
"intentName": "HELP"
},
"fulfillment": {
"speech": "",
"messages": [
{
"type": 0,
"speech": ""
}
]
},
"score": 1
},
"status": {
"code": 206,
"errorType": "partial_content",
"errorDetails": "Webhook call failed. Error: Request timeout.",
"webhookTimedOut": true
},
"sessionId": "f761206e-76d4-4a08-b95d-57a39694cb00"
}
using
Dim jsonResulttodict = JsonConvert.DeserializeObject(Of Dictionary(Of
String, Object))(decodedString)
I can get the id value by: var_id = jsonResulttodict.Item("id")
how do I get the values that are deeper, like the value of resolvedQuery that is below result ?
and also the value of intentName under metadata which is under result....
Thank you
I have the following JSON that I am looking to convert into a GridView. I have been able to successfully do this for a portion of the JSON. It seems to fail on the deposit and withdrawals section. Anyone have any suggestions?
{
"results": [
{
"id": "51142254",
"tp_id": "!XP4D49X0CD123628",
"firstname": "Owner",
"lastname": "Operator",
"email": "",
"phone": "",
"enrolled": "1",
"balance": 247.54,
"fleet": "Test Express",
"deposits": [
{
"id": "184022380",
"date": "2016-02-17",
"amount": "200.00",
"transID": "135246",
"memo": "Scheduled Deposit",
"status": "Cleared"
},
{
"id": "184022383",
"date": "2016-02-25",
"amount": "200.00",
"transID": "246357",
"memo": "Scheduled Deposit",
"status": "Cleared"
},
{
"id": "184022386",
"date": "2016-03-02",
"amount": "200.00",
"transID": "975468",
"memo": "Scheduled Deposit",
"status": "Cleared"
}
],
"withdrawals": [
{
"id": "184026949",
"date": "2016-03-09",
"amount": "352.46",
"transID": "395920",
"memo": "Invoice\r\n\r\n100234",
"status": "Cleared"
}
]
},
{
"id": "51142326",
"tp_id": "!XP4D49X7CD123612",
"firstname": "Owner",
"lastname": "Operator",
"email": "",
"phone": "",
"enrolled": "1",
"balance": 0,
"fleet": "Test\r\nExpress",
"deposits": [],
"withdrawals": []
}
]
}
This is the current code I use for GridView.
Dim UserList As List(Of api_Test_Deposit) = JsonConvert.DeserializeObject(Of List(Of api_Test_Deposit))(GetUrlString(searchType, searchValue))
Dim table = JsonConvert.DeserializeObject(Of DataTable)(GetUrlString(searchType, searchValue))
Return table
Below is my JSON response data, I need to do assertion using the below response. I tried in many ways to write JSON path & Expected Value. Always assertion fails. What I want is please help to write the path and expected value for the below data
{
"statusCode": 200,
"statusMessage": "Success",
"errorMessage": "",
"responseData": {
"id": 15,
"userName": "partner#tarento.com",
"firstName": "tarento",
"lastName": "test1",
"phoneNumber": "1234567812",
"email": "partner#tarento.com",
"password": "",
"city": "",
"agentList": [
{
"id": 37,
"userName": "Rahul.antonyRaj#tarento.com",
"firstName": "Sanjay",
"lastName": "rahul",
"phoneNumber": "7411269480",
"email": "Rahul.antonyRaj#tarento.com",
"password": "",
"active": true
},
{
"id": 68,
"userName": "jinesh.sumedhan#tareto.com",
"firstName": "jinesh",
"lastName": "sumedhan",
"phoneNumber": "9400993826",
"email": "jinesh.sumedhan#tareto.com",
"password": "",
"active": true
},
{
"id": 108,
"userName": "a.sanjayrahul#gmail.com",
"firstName": "Rahul",
"lastName": "Antony",
"phoneNumber": "9994590241",
"email": "a.sanjayrahul#gmail.com",
"password": "",
"active": true
},
{
"id": 304,
"userName": "a.sanjayrajish#gmail.com",
"firstName": "Agent",
"lastName": "Agent",
"phoneNumber": "9025699716",
"email": "a.sanjayrajish#gmail.com",
"password": "",
"active": true
}
],
"roleName": "admin",
"sessionKey": "435tnerLt9813942160478oDse46345635#1",
"partner": {
"id": 1,
"name": "Tarento",
"cityList": [
"bangalore",
"mumbai"
],
"phone": "1234567812",
"url": ""
},
"isActive": true,
"isDeleted": false,
"roleId": 1,
"countryCode": "",
"tags": [
{
"tagId": 1,
"name": "all",
"description": "this is default tag of all driver."
},
{
"tagId": 2,
"name": "airport",
"description": ""
},
{
"tagId": 3,
"name": "street",
"description": "any text message"
},
{
"tagId": 255,
"name": "night",
"description": "night"
}
]
}
}
I received the following response
For start following JSONPath Assertion will test your statusCode
$.statusCode
put 200 to Expected Value of JSONPath Assertion.
This one is for userName
$.responseData.userName
Easy, isn't it? See Parsing JSON guide for more useful examples and how-tos.
I found the JSR223 Assertion with script language javascript to be the easiest. at least if you have knowledge in java and javascript. And no need to add any plugins.
My working code in detail:
var json = JSON.parse(SampleResult.getResponseDataAsString());
if (json.statusCode != 200) {
AssertionResult.setFailureMessage(""
+ json.statusCode
+ " " + json.statusMessage
+ " " + json.errorMessage);
AssertionResult.setFailure(true);
}
I personally prefer to use BSF PostProcessor in coupling with Groovy language. Example of how to parse JSON with Groovy you can find here how to parse json using groovy