user2661518 user2661518 - 5 months ago 17
JSON Question

Convert string to json data

I am converting string to json format as below

data = """

accept reply: true


And json data is

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

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


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.


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