Search code examples
pythonjsonargs

Parse args to json elements in python


i have a data structure that i want to fill with cmd args

params = {
  ...
  ...
  "blockX": "{\"nameX\":["\Arg1\","\Arg2\",\"Arg3\"........"\ArgX\"]}",
  ...
  ...
}

Then i run a post request with the params as data:

r = requests.post("https://url", data=params)

I only know how to do it with one element

"BlockX": "{\"nameX\": \"%s\"}" %ArgX,

Regards


Solution

  • Your example suggest you want to join the arguments. You can convert any list into a single string by merging with a separator:

    args = ['foo', 'bar', 'hold the mustard']
    print('", "'.join(args))
    

    So to get your list '"Arg1", "Arg2"' etc, join them with the '", "' separator and insert that into your template:

    '{"nameX": ["%s"]}' % '", "'.join(args)
    

    Note how ' allows you to skip escaping each ". In your example, this would look like:

    params = {
      #...
      "blockX": '{"nameX": ["%s"]}' % '", "'.join(args),
      # ...
     }
    

    Please keep in mind that you are putting a string representation of a JSON into a JSON! This is... perhaps not the right thing to do. A proper API would expect just a single JSON, in which case you can dump args directly.

    params = {
      #...
      "blockX": {
        "nameX": args
      },
      # ...
     }