I have a list of two DataTables. I'm converting this list to a JSON array, but I need to add the table name for every DataTable in the JSON string.
How can I do that?
This is how I'm converting the list:
Dim json As String = JsonConvert.SerializeObject(list, New DataTableConverter())
Desired JSON output:
{
"category": [
{
"id": "1",
"desc": "default",
},
{
"id": "2",
"desc": "fun",
}
],
"images": [
{
"image ID": "1",
"link": "images/logo.jpg"
"category": "1"
},
{
"image ID": "2",
"link": "images/logo2.jpg"
"category": "2"
}
]
}
Try putting your tables into a DataSet instead of a list, then serialize the DataSet.
Dim table1 As New DataTable("category")
table1.Columns.Add("id", GetType(String))
table1.Columns.Add("desc", GetType(String))
table1.Rows.Add("1", "default")
table1.Rows.Add("2", "fun")
Dim table2 As New DataTable("images")
table2.Columns.Add("image ID", GetType(String))
table2.Columns.Add("link", GetType(String))
table2.Columns.Add("category", GetType(String))
table2.Rows.Add("1", "images/logo.jpg", "1")
table2.Rows.Add("2", "images/logo2.jpg", "2")
Dim dataSet As New DataSet()
dataSet.Tables.Add(table1)
dataSet.Tables.Add(table2)
Dim json As String = JsonConvert.SerializeObject(dataSet, Formatting.Indented)
Console.WriteLine(json)
Output:
{
"category": [
{
"id": "1",
"desc": "default"
},
{
"id": "2",
"desc": "fun"
}
],
"images": [
{
"image ID": "1",
"link": "images/logo.jpg",
"category": "1"
},
{
"image ID": "2",
"link": "images/logo2.jpg",
"category": "2"
}
]
}
Related
Trying to achieve this by using the following script, which I want to extend with a loop to loop through the input. This should filter on the objects with have the value "valse", the others should be deleted/replaced.
def Message processData(Message message) {
//getBody & new jsonSlurper
def body = message.getBody(java.lang.String) as String
def data = new JsonSlurper().parseText(body)
if (data.value != "false") {
body = body.replaceAll(~/^(.*?)\childNodes/, "")
message.setBody(body);
} else {
}
return message
}
Input:
[{
"name": "1",
"value": "true",
"childNodes": [{
"name": "2",
"value": "true",
"childNodes": [{
"name": "3",
"value": "false",
"childNodes": [{
"name": "4",
"value": "false"
}]
}]
}]
}]
Desired output:
[{
"name": "3",
"value": "false",
"childNodes": [{
"name": "4",
"value": "false"
}]
}]
import groovy.json.*
def body ='''
[{
"name": "1",
"value": "true",
"childNodes": [{
"name": "2",
"value": "true",
"childNodes": [{
"name": "3",
"value": "false",
"childNodes": [{
"name": "4",
"value": "false"
}]
}]
}]
}]
'''
def filter(arr){
for(i in arr){
if(i.value == 'false') return [i]
def filteredChild = filter(i.childNodes)
if(filteredChild)return filteredChild
}
return null // not found
}
def filtered = filter( new JsonSlurper().parseText(body) )
println new JsonBuilder(filtered).toPrettyString()
Assuming you have only a single child object every time and that your task is finding the first value=false node and returning it with all the child nodes, you can do the following:
def processData(String message) {
def data = new JsonSlurper().parseText(message)[0]
while (data.value != 'false') { data = data.childNodes[0] }
return new JsonBuilder([data]).toPrettyString()
}
Here's a Spock test to go with it (replaced pretty string with regular json string so that it's easier to compare strings with ==)
class ParseSpec extends Specification {
def testString = '''
[{
"name": "1",
"value": "true",
"childNodes": [{
"name": "2",
"value": "true",
"childNodes": [{
"name": "3",
"value": "false",
"childNodes": [{
"name": "4",
"value": "false"
}]
}]
}]
}]
'''
def processData(String message) {
def data = new JsonSlurper().parseText(message)[0]
while (data.value != 'false') { data = data.childNodes[0] }
return JsonOutput.toJson([data])
}
def 'run test'() {
expect:
'''[{"name":"3","value":"false","childNodes":[{"name":"4","value":"false"}]}]''' == processData(testString)
}
}
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.
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'm pretty new to Groovy (and json) and being playing around with this code trying to get it to work, almost but not quite getting there and need a little help...
So what I'm trying to do is parse an existing json file and then add/append additional entries as in below example:
Original Json
{
"organisation": "company",
"modules": [
{
"description": "Module 1",
"type": "Q1",
},
{
"description": "Module 2",
"type": "Q2",
},
{
"description": "Module 3",
"type": "Q3",
}
]
}
New Json
modules {
description 'Module 4'
type 'TEST'
}
Intended Final Output
{
"organisation": "company",
"modules": [
{
"description": "Module 1",
"type": "Q1",
},
{
"description": "Module 2",
"type": "Q2",
},
{
"description": "Module 3",
"type": "Q3",
},
{
"description": "Module 4",
"type": "TEST",
}
]
}
I've tried many variations on the following code snippet but still not quite getting the right format for my intended output
def inputFile = file("modules.json")
def outputFile = new File("modules.new.json")
def json = new JsonSlurper().parseText(inputFile.text)
println "This is our original input JsonSlurper: \n"
println JsonOutput.prettyPrint(JsonOutput.toJson (json))
def builder = new JsonBuilder()
def jsonNew = builder {
modules {
description 'Module 4'
type 'TEST'
}
}
println "This is our combined output JsonBuilder: \n"
println JsonOutput.prettyPrint(JsonOutput.toJson ([json, jsonNew]))
Which results in the below:
[
{
"organisation": "company",
"modules": [
{
"description": "Module 1",
"type": "Q1"
},
{
"description": "Module 2",
"type": "Q2"
},
{
"description": "Module 3",
"type": "Q3"
}
]
},
{
"modules": {
"description": "Module 4",
"type": "TEST"
}
}
]
Any help sorting this would be much appreciated.
You need to merge maps before produce json:
json.modules = json.modules << jsonNew.modules
println JsonOutput.prettyPrint(JsonOutput.toJson(json))
[json, jsonNew] this just creates an array of objects, it's not adding the new object into the json.modules array.
I am trying to utilize the JSON result of a GET request to my Li3 app, but I would like the result to be an array of the returned JSON objects, rather than an object of the JSON objects.
I have the following code in my view file (index.html.php):
print($todos->to('json'));
Which results in each row becoming a JSON object (good), but within an over-arching JSON object.
{
"1": {
"id": "1",
"title": "One",
"done": "0"
},
"2": {
"id": "2",
"title": "Two",
"done": "0"
},
"3": {
"id": "3",
"title": "Three",
"done": "0"
},
"4": {
"id": "4",
"title": "Four",
"done": "0"
}
}
I would like to get:
[
{
"id": "1",
"title": "One",
"done": "0"
},
{
"id": "2",
"title": "Two",
"done": "0"
},
{
"id": "3",
"title": "Three",
"done": "0"
},
{
"id": "4",
"title": "Four",
"done": "0"
}
]
Note: I've found that this was the case (array of objects) in commit "974469cf25db5cbab61f3e1ff172405f4635032e" of the lithium github project, but with anything after that commit, the result is an object of objects.
Try $todos->to('json', ['indexed' => false]), or, refer to the Media class for direct serialization of JSON without the template.
Todos::all(['return' => 'array'))->to('json'); works perfect with RecordSet too