简体   繁体   English

在python中将参数解析为JSON字符串

[英]Parse argument to JSON string in python

I want to do following in my python script: 我想在我的python脚本中执行以下操作:

d = {"dpid": + sys.argv [1] + ,"flow_id" : "flow0001"," "actions":{"output":2}}

Its a JSON string further I am loading in my application, can any help, how should I parse that argument in the string ? 我在应用程序中进一步加载了它的JSON字符串,有什么帮助,我应该如何解析字符串中的该参数?

Your code is incorrect. 您的代码不正确。 Replace it with: 替换为:

d  = "{\"dpid\":" + sys.argv[1] + ",\"flow_id\":\"flow0001\",\"actions\":{\"output\":2}}"

Make sure the argument you type is an integer. 确保您键入的参数是整数。 If you want to parse the json string and get the dpid later, write this (python 3 code): 如果要解析json字符串并在以后获取dpid,请编写以下代码(python 3代码):

import json
j = json.loads(d)
print(j['dpid'])

If your file name is test.py Then pass args like below 如果您的文件名为test.py,则按如下所示传递args

$ python test.py arg1 arg2 arg3

in test.py file you can access them as string by str(sys.argv[index]) 在test.py文件中,您可以通过str(sys.argv [index])以字符串形式访问它们

in your scenario 在你的情况下

d = '{"dpid":"' + str(sys.argv [1]) +'" ,"flow_id":"flow0001", "actions":{"output":2}}'

then parse that string as below, 然后按以下方式解析该字符串,

import json
obj = json.loads(d)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM