Home > Back-end >  How to convert input arguments to program as json in python
How to convert input arguments to program as json in python

Time:05-14

Here is my code

import json
import sys

def main():
    payloads=sys.argv[2]
    payloads=payloads.replace(",",",\"")
    payloads=payloads.replace(":","\":")
    payloads=payloads.replace("{","{\"")
    z=json.loads("'" payloads "'")
    print(payloads)

if __name__ == "__main__":
    main()

The input can not be changed as its auto generated and I need to parse it inside the python code to get individual values. How can this be done, p.s. I am not python expert

When i try to run it in command prompt as below (in single line):

python test.py payload: "{"temperature":20,"humidity":80,"pressure":1000,"timestamp":1652419592750,"deviceid":"device1"}" 

I see below error:

Traceback (most recent call last):
  File "test.py", line 14, in <module>
    main()
  File "test.py", line 10, in main
    z=json.loads("'" payloads "'")
  File "python3\lib\json\__init__.py", line 346, in loads
    return _default_decoder.decode(s)
  File "python3\lib\json\decoder.py", line 337, in decode
    obj, end = self.raw_decode(s, idx=_w(s, 0).end())
  File "python3\lib\json\decoder.py", line 355, in raw_decode
    raise JSONDecodeError("Expecting value", s, err.value) from None
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0)

CodePudding user response:

Put single quotes around the argument, then all the double quotes will be preserved, and you don't need to do any replacing in Python.

import json
import sys

def main():
    payloads=sys.argv[2]
    z=json.loads(payloads)
    print(payloads)

if __name__ == "__main__":
    main()
python test.py payload: '{"temperature":20,"humidity":80,"pressure":1000,"timestamp":1652419592750,"deviceid":"device1"}'

CodePudding user response:

The easyest way to solve your problem would be to add good quotes to the input but if you can't, you can use this

import json, sys

def main():
    payloads=sys.argv[2]
    payloads=payloads.replace(",",",\"")
    payloads=payloads.replace(":","\":")
    payloads=payloads.replace("{","{\"")


    for x in payloads.split(","):
        
        value = x.split(":")[1].replace("}", "")

        try:
            int(value)
            float(value)
            assert value not in ("true", "false", "null")

        except (AssertionError, ValueError):
            new = x.replace(value, f'"{value}"')
            payloads = payloads.replace(x, new)

    
    z=json.loads(payloads)
    print(payloads)

if __name__ == "__main__":
    main()

note however that this way can cause a lot of bugs if your input data ever contains the characters }, : or ,

  • Related