2

I've been trying to send some integer values over socket to a LabVIEW client using json.dumps but as the numbers change the size of each field may change, I would like to know if there is a way to pad the number with '0' without turning it into a string when I do the json dump, as it adds " " to the packet send around each number.

Example:

data = json.dumps({"Data": str(52).zfill(4)]})
self.sock.send(data.encode())

This sends

'"Data":"0052"'

I want

'"Data": 0052'
  • Leading zeros are simply not allowed in JSON ints. See https://stackoverflow.com/questions/27361565/why-is-json-invalid-if-an-integer-begins-with-0/27361630#27361630 – jasonharper Dec 04 '18 at 20:58
  • Why is it a problem that 'the size of each field may change' - is the LabVIEW client written in a way that can't handle this? Do you have access to the LabVIEW code? – nekomatic Dec 05 '18 at 09:33
  • I would like to send a big packet and do several tcp reads with a fix size to parse the information, as in every 7 values or so. – Diego Ernesto Mendez Fuentes Dec 05 '18 at 14:20
  • Then why JSON?; Why not send packets that lay out only what you need in a fixed string? – FraggaMuffin Dec 05 '18 at 23:01

1 Answers1

1

As @jsonharper mentioned, technically what you're asking for is no longer JSON, more on that here

However, that doesn't mean you can't use the json library to do the bulk of the work for you!

You can achieve this by passing a custom encoder class to json.dumps like this:

>>> import json

>>> class MyInt(int):
...     def __str__(self):
...         return '{:0>4}'.format(self)

>>> class MyEncoder(json.encoder.JSONEncoder):
...     def default(self, o):
...         if isinstance(o, MyInt):
...             return str(o)
...         return super(MyEncoder, self).default(o)

>>> obj = {'Data': MyInt(52)}
>>> json.dumps(obj, cls=MyEncoder)
'{"Data": 0052}'

You can do this with any class, but this can result in something that can't be decoded again with a strict JSON decoder.

See if you can get LabVIEW to read standard JSON, but if not, the above should work.

FraggaMuffin
  • 3,915
  • 3
  • 22
  • 26
  • LabVIEW does have functions to read/generate json in string -> flatten/unflatten. If the JSON structure is known and constant, simply create a cluster reassembling the same structure, and let LabVIEW read the JSON data into the cluster and v.v. – sweber Dec 17 '18 at 20:19