user2661518 user2661518 - 4 months ago 9
JSON Question

Convert string to json data

I am converting string to json format as below

data = """

S3F4
accept reply: true

"""


And json data is
[{"header":{"stream":3,"function":4,"reply":True}}]


I can use regex and search pattern
S3F4
and add to dict.

But is there any better way or in build functions I can use for more generic solution?

Answer

Not sure about all the variations of the input string and what is the scope of characters stream, function and reply can have, but here is what you can start with:

S(?P<stream>\d)F(?P<function>\d)\naccept reply: (?P<reply>\w+)

where (?P<...>...) are named capturing groups, \d would match a single digit, \w+ would match one or more consecutive alphanumeric (and underscore) characters.

Demo:

>>> import re
>>> 
>>> data = """
... S3F4
... accept reply: true
... """
>>> 
>>> match = re.search(r"S(?P<stream>\d)F(?P<function>\d)\naccept reply: (?P<reply>\w+)", data)
>>> print(match.groupdict())
{'function': '4', 'reply': 'true', 'stream': '3'}