Low Code examples from other languages

Sorry Norm, I really don’t understand your point :confused:
json is part of Python’s standard library and you always have to import the modules you use.
.

Imo this is the kind of task that dynamic languages make easy. Arrays, objects, arrays of objects, objects containing arrays, whatever…
Here’s an example of some quite complex JSON returned by the Betfair API:

{
"jsonrpc": "2.0",
"id": 1,
"result": [
    {
        "marketId": "1.113197547",
        "marketName": "FC Betlemi Keda +1",
        "marketStartTime": "2014-03-13T11:00:00.000Z",
        "totalMatched": 12,
        "runners": [
            {
                "selectionId": 6843871,
                "runnerName": "FC Betlemi Keda +1",
                "handicap": 0,
                "sortPriority": 1,
                "metadata": {
                    "runnerId": "63123618"
                }
            },
            {
                "selectionId": 6830600,
                "runnerName": "FC Samtredia -1",
                "handicap": 0,
                "sortPriority": 2,
                "metadata": {
                    "runnerId": "63123619"
                }
            },
            {
                "selectionId": 151478,
                "runnerName": "Draw",
                "handicap": 0,
                "sortPriority": 3,
                "metadata": {
                    "runnerId": "63123620"
                }
            }
        ],
        "eventType": {
            "id": "1",
            "name": "Soccer"
        },
        "competition": {
            "id": "2356065",
            "name": "Pirveli Liga"
        },
        "event": {
            "id": "27165685",
            "name": "FC Samtredia v FC Betlemi Keda",
            "countryCode": "GE",
            "timezone": "GMT",
            "openDate": "2014-03-13T11:00:00.000Z"
        }
    }
]
}

And this shows how easy it is to pick out a deeply nested detail using Python:

import json
js = json.loads(jsonData) # jsonData being the above as a string
print(js["result"][0]["runners"][0]["runnerName"])

# FC Betlemi Keda +1
1 Like

Whether its part of the std library, a nugget package, or a plugin really isnt the key
Its NICE that it is - but I can be quite sure python did not start out having json in their std library
Or many other things
They’ve been added to many languages over time in various ways

But, in Sam’s post what IO didnt really is not only does it deserialize NOT just to a string or dictionary or whatever
It reconstitutes the entire data structure; apparently regardless of the complexity

I dont know python etc to know if they do that as well ?

This misses the point that Sam was making
Picking out an item isnt what his code did

1 Like

I think Python does that too with JSON data.

When data is something else than maps and arrays, I would probably use MessagePack.

And that was Sam’s point
He can use structures & other native language items and serialize & deserialize to from the user created structures with one line
Not just to from arrays & dictionaries (which many other langs seem to do)

THAT is VERY low code if I can make what ever data structure I want and with one line serialize it and with another line deserialize it

1 Like

Yeah, but he used ‘JSONDecoder()’ on his example and I don’t think it handles other than strict JSON based data?

I can use MessagePack to serialize/deserialize any 8th item using ‘b:>mpack’ and ‘b:mpack>’ words:

ok> d:new

ok> .s

1    d: 0000000003361f00 1  2024-02-21T20:41:52+02:00

ok> b:>mpack

ok> .s

2    T: 00000000033a1430 1  true
1    b: 00000000035e97c0 1  000000000000001b Xc7010a01d40864d2000b4679ce0470f713d200001c20ce00000000

ok> drop

ok> b:mpack>

ok> .s

2    T: 00000000033a1430 1  true
1    d: 0000000003361f00 1  2024-02-21T20:41:52+02:00

ok>

I truly have NO idea what that demonstrates
Nor do I have the time to decipher it
But maybe its the same principle

It’s a REPL session showing stack contents before and after serializing 8th date into MessagePack binary buffer and after deserializing that buffer back into 8th date. The ‘.s’ word prints the stack contents.

Utterly incomprehensible. Glad it works for you though. :slight_smile:

A Python dictionary is a direct equivalent of a JavaScript object which is what JSON was created to serialize / deserialize :man_shrugging:

so if I had

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age

p1 = Person("John", 36)

that gives me one instance in python (Correct ?)

and if I serialize that how do I do that ?
Sam’s was one line to serialize an array of instances
@samRowlands correct me if I’m wrong here

And if I deserialize that do I get back an instance as well ?

Just asking as I dont write python so …

1 Like

You’re not wrong. The project I lifted that code from only stored an array of objects. The main project I’m working has a far more complex data model, and still only requires the same code to serialize and de-serialize.

I know that pLists are supported as well, but I haven’t gotten that far to store my data model in a plist, of which there are two types. XML and binary.

Wait until you see how much code it takes to store a data model in a SwiftData database… “@Model” annotation on the class declaration. Then you just interact with the class… I’ve not yet tried it as it requires macOS 14 or newer, but even still, it is pretty mind blowing compared to what I’ve had to do with Xojo.

import SwiftData

// Annotate new or existing model classes with the @Model macro.
@Model
class Trip {
    var name: String
    var destination: String
    var startDate: Date
    var endDate: Date
    var accommodation: Accommodation?
}

2 Likes
import json

class Person:
  def __init__(self, name, age):
    self.name = name
    self.age = age
    
jsonData = """
[
    { "name": "Norm", "age": 21 },
    { "name": "Sam", "age": 18 }
]
"""

# one line to deserialize the json to an array of Persons ...
people = [ Person(x['name'], x['age']) for x in json.loads(jsonData) ]

# confirm our output ...
for p in people: print(type(p), p.name, p.age)

# and one line to do the reverse ...
jsonData = json.dumps([{'name': x.name, 'age': x.age} for x in people])

# confirm the result ...
print(jsonData)
1 Like

After Xojo, I will not invest in a single person or small team software. Sorry.

3 Likes

What I’d give to have my 18 year old body back!

2 Likes

Actually it’s just occurred to me instead of doing this:

jsonData = json.dumps([{'name': x.name, 'age': x.age} for x in people])

I could just do this:

jsonData = json.dumps([ x.__dict__ for x in people ])

.

I’ve been working on exactly that for 5 months now. I haven’t seen my six-pack for > 20 years but it’s just starting to re-emerge :muscle:

1 Like

Mine too
But I have to deal with the other 18 cans :stuck_out_tongue:

Nice !

THATS the same kind of “low code” Sam was showing

Something that Xojo simply doesnt have built in
Could it? is an entirely different question

1 Like

In Python there’s no real need to turn something that’s just data into a class but you certainly can do it, even adding in new members you didn’t originally define:

import json

class Thingy:
    def __init__(self, d):
        if isinstance(d, dict):
            for key, value in d.items():
                setattr(self, key, value)
                
    def __str__(self):
        return str(self.__dict__)
    
jsonData = """
[
    { "name": "Norm", "age": 21, "country": "CA", "likes": ["Beer", "Ice Hockey"] },
    { "name": "Sam", "age": 18, "country": "TW" }
]
"""

things = [ Thingy(x) for x in json.loads(jsonData) ]
for x in things:
    print(x.name, x.age)
    print(str(x))

Dunno python well enough to form ANY opinion about needing / not needing classes

My background WOULD encourage me to do so because I like being able to add class methods etc
There maybe a way to do something else in Python that means that design style isnt as useful there

Dunno

I’m almost at the same weight as I was when I was 18, but what I want from my 18 year self is less physical pain. In 3 weeks, I’m hoping to go on some new (to me) Immunosuppressants that should reduce the physical pain I have to go through every day.

If someone tells you that a diet and herbal meds for 3 months ,can fix auto-immune disorders, walk away, in fact run (if you can). Oh, I did lose 3 kilos (6.6 lbs) in one month!