I'm asking this after some researchs on internet. There's a way to JSON type or XML type files to import Excel sheet but there's no clear descriptions found for my case. I would like to what is my goal;
I have a some type of string data like .txt file like this;
Example Data:
{"vehicle1": {
"title": "A super red vehicle",
"weight": "1500 kg",
"height": "2 m",
"vehicle1-center_of_gravity": [
{"x": "2 m"},
{"y": "-0.5 m"},
{"z": "1.5 m"}
"vehicle1-passenger_weights": [
{"p1": "2 m"},
{"p2": "-0.5 m"},
{"p3": "1.5 m"}
"color": "red",
]
}
}}
I would like to select this file with file dialog and then click to read button now my question comes in here. Is it possible to link/map them with cells for example i have cell named vehicle_title and i want to map this cell with .txt file's "title": "A super red vehicle".
Do you have any experience or idea how can i implement that to my macro.
Regards.
You can use this library
https://github.com/VBA-tools/VBA-JSON
to parse JSON in VBA, but you'll need to do the mapping in code: there's no built-in configuration/wizard for this.
Sub Tester()
Dim j As Object, json As String, v
'read from file
json = CreateObject("scripting.filesystemobject").OpenTextFile( _
ThisWorkbook.Path & "\example.txt").ReadAll()
'import module from: https://github.com/VBA-tools/VBA-JSON
Set j = JsonConverter.ParseJson(json)
Set v = j("vehicle1")
'some attributes...
Debug.Print v("title")
Debug.Print v("weight")
Debug.Print v("vehicle1-center_of_gravity")(1)("x")
End Sub
PS there are a few syntax errors in your JSON sample.
Related
I'm trying to extract data from a nested array in a JSON file, but I don't manage to get these. In this example, I want to get the IDs.
"order-lines": [
{
"id": 12610
},
{
"id": 12611
}
],
For now I'm using this code but it doesn't work.
Set Json = ParseJson(oRequest.responseText)
For Each Item In Json
Cells(i, 4).Value = Item("order-lines")(1)("id")
Next
Can you please help me?
Thank you in advance
Anybody create the Excel VBA code for the following json file ?
"Version": "1.1",
"TranDtls": {
"TaxSch": "GST",
"SupTyp": "B2B",
"IgstOnIntra": "N",
"RegRev": "N",
"EcmGstin": null
},
"DocDtls": {
"Typ": "INV",
"No": "1",
"Dt": "21/10/2022"
Excel VBA code for the JSON file CREATION
We need some more information to help you find the correct answer. Do you want to read/import this json string or do you want to have Excel create such a string for export?
You can use the VBA-JSON module from github. A simple way to create the string is to copy paste it into a string variable and use the Replace function;
sTemp = "... "TaxSch": "[TaxSch]",....
sJson = Replace(sTemp,"[TaxSch]", Yourvalue)
Or you could use concatenation but that will be more difficult with all the quotes.
Now I have a string in format dict but as i can guess its a json format its look like:
{
"gid":"1201400250397201",
"memberships":[
"can be nested objects",
...
],
"name":"Name of task",
"parent":{
"gid":"1201400250397199",
"name":"name of parent task"
},
"permalink_url":"https://url...."
}
So first question: am i right? I used dumps() from json library but got unicode escape sequences, loads() didnt work for me, i got error "the JSON object must be str, bytes or bytearray, not dict".
Second question: if its not json format, how can i get comfortable view? I did it:
first of all i get dict-line, then I print a dictionary's key:
for key in task:
task
print(task[key])
output:
1201400250397201
[]
Name of task
{'gid': '1201400250397199', 'name': ''name of parent task'}
https://url....
At actually it would be great if I get something like that:
gid: 1201400250397201
name: Name of task
parent_name: 'Name of task' etc
But I dont know how to get it :(
Next question: as you can see for part "parent" (penultimate line) I also get dictionary, how can I extract it and get convenient format?
Or maybe you have your comfortable methods?
Like stated in your error, the object you are working with is already a dictionary. You can print it directly as json with json.dumps:
task = {'gid': '1201400250397201', 'memberships': [{}], 'name': 'Name of task', 'parent': {'gid': '1201400250397199', 'name': 'name of parent task'},'permalink_url': 'https://url....'}
print(json.dumps(task, indent=4))
Setting indent=4 makes it readable and you'll get:
{
"gid": "1201400250397201",
"memberships": [
{}
],
"name": "Name of task",
"parent": {
"gid": "1201400250397199",
"name": "name of parent task"
},
"permalink_url": "https://url...."
}
If you don't want unicode characters to be escaped, add the argument ensure_ascii=False:
print(json.dumps(task, indent=4, ensure_ascii=False))
I'm trying to validate some JSON files on VB.net.
However, Whenever I run my code it gets stuck on
Dim Schema As JsonSchema = JsonSchema.Parse(SchemaString)
The Error Says
An unhandled exception of type 'Newtonsoft.Json.JsonException' occurred in Newtonsoft.Json.dll.
There is also a warning that says that JSON validation moved to its own package. So, I'm pretty sure I'm just importing the wrong packages, but I'm not sure.
I would be grateful if anyone could point me in the correct direction,
Thank you.
Here is my VB.net code
Imports System
Imports Newtonsoft.Json.Schema
Imports Newtonsoft.Json.Linq
Public Function Validate_JSON()
Dim SplunkPath As String = "Z:\Database Project\Splunk Folder\Dropbox\Splunk_File.json"
Dim SchemaPath As String = "Z:\Database Project\Schema Folder\Schema_File.json"
Dim Schema_String As String = My.Computer.FileSystem.ReadAllText(SchemaPath)
Dim Schema As JsonSchema = JsonSchema.Parse(Schema_String)
Dim Data_String As String = My.Computer.FileSystem.ReadAllText(SplunkPath)
Dim Data_JSON As JObject = JObject.Parse(Data_String)
Dim Splunk_Status As Boolean = Data_JSON.IsValid(Schema)
Return 0
End Function
Here is Splunk_File.json
{
"Site": "USI",
"SN": "21165",
"MN": "F2C00W",
"DateTime": "05/18/2021"
}
Here is Schema_File.json
{
"$schema" :"http://json-schema.org/draft-04/schema",
"properties": {
"$schema": "#",
"Site": {
"type": "string"
},
"SN": {
"Type": "string"
},
"MN": {
"Type": "string"
}
}
}
$schema is only valid at the root, and properties values MUST be schemas.
You have a "$schema" : "#" inside properties. This means that you're trying to say that your JSON object should have a property called schema that can validate against the schema #. But # isn't a valid schema object, so the parse fails.
You need to remove the $schema from your properties.
I'd also suggest using a later draft of the schema spec (if you have control over the schema). Draft 6 is the oldest version that's compatible with the latest, 2020-12.
But for this you'll likely need to use a different validation package. There are several available. Mine is JsonSchema.Net.
I'm working on a tkinter program where I store some data in a json file and load that data into a treeview object (tkinter widget). Thats working all fine. I can update the fields in the treeview also just fine. But how do I save that data and override my json file? I keep hitting the wall on this. Heres my not working code (I know the string is not correct, it's just gorillacode):
data = {}
data['people'] = []
for row_id in my_tree.get_children():
row = my_tree.item(row_id)["values"]
string = "name": "+row[0]+", "birthdate": "+row[1]+"
data['people'].append({string})
with open('birthdays.json', 'w') as outfile:
json.dump(data, outfile)
The output in the json file have to end up looking like this:
{"people": [{"name": "Vincent", "birthdate": "08/01/2011"}, {"name": "Josephine", "birthdate": "08/01/2011"}, {"name": "Athena", "birthdate": "24/01/2012"}]}
I figured out it was easier to do a .write(string)
I had some backslashes in the file that i removed before with .replace().
ended up working fine for me.