LabVIEW

cancel
Showing results for 
Search instead for 
Did you mean: 

How to match on union JSON similar to Typescript

Solved!
Go to solution

Example 1:

{
"kind": "label",
"value": "this is the label"
}

Example 2:
{
"kind": "command",
"value": 32,
"step": 5,
"message": "message"
}

I was using the BlueSerialization package from blue origin. But am am running into this issue.

 

In typescript I can union between different interfaces and match on the "kind" value which is essentially a string enum. 
https://medium.com/@meetpujara02/understanding-union-types-in-typescript-a-deep-dive-36b27eeae808 

 

How can i mirror this behavior in labview? Essentially the payload is json and it can look different. What is considered best practice? In my case, I will actually be receiving an array of these payloads. Each one can be different in the array. How can i safely match on each to ensure the payload is valid?

 

thank you,

 

 

 

0 Kudos
Message 1 of 6
(266 Views)

There is this JSON parser:

 

https://www.ni.com/en/support/downloads/tools-network/download.jsontext.html#405275

 

It includes a (limited) form of JSONPath to work with JSON.

 

https://jsonpath.com/

 

I have not used the JSONPath portion of it personally but it sounds like that might be what you're looking for.

0 Kudos
Message 2 of 6
(221 Views)

I think the JSONText library has JSON Schema support, which is intended to validate incoming JSON. I believe the JSON Schema enum type would do what you're looking for: https://json-schema.org/understanding-json-schema/reference/enum

 

0 Kudos
Message 3 of 6
(198 Views)
Solution
Accepted by topic author elibarber

Hi elibarber,

 

Union types do not exist as you have in TypeScript.

 

The closest I can see would be:

 - A variant containing a cluster, specific to the kind of payload ;

 - A string containing a flattened/binary version of the same cluster ;

 - A class hierarchy with a subclass for each kind of payload.

 

I would personally choose the class hierarchy for scalability, but it can be a challenge for new LabVIEW users.

Attached is an example where I used the JSONtext toolkit function with a custom Object Serializer to deserialize an array of mixed type objects.

 

Regards,

Raphaël.

Message 4 of 6
(197 Views)

Wow. Insane. OOP is not my strength with LabVIEW, but I was able to recreate or example with 30 classes for each command and it works! 

 

Thank you, this is perfect. I know I will need need to plan for future payloads and this is should scale perfectly for when that time comes.

0 Kudos
Message 5 of 6
(123 Views)

@elibarber wrote:

Thank you, this is perfect. I know I will need need to plan for future payloads and this is should scale perfectly for when that time comes.


If my answer solved your issue, don't forget to 

Accept as Solution.png

0 Kudos
Message 6 of 6
(68 Views)