我正在尝试基于JSON响应获取Python变量。
当我请求JSON时,我想将一些信息另存为
X = content[0]['OrderItemList'][0]['ItemID']
我需要的是变量X
,如果它是某个数字,则要更改。
例如,如果x = 3
,我需要将其更改为x = 5
。到目前为止,我已经能够通过数学和其他字符串或整数更改来更改变量。我认为循环会起作用,但我不确定。
if request.method == 'POST':
x = content[0]['OrderItemList'][0]['ItemID']
pseudocode
if x = 2 chnage to x = 5
答案 0 :(得分:1)
只需将x设置为json中的值,然后使用if/elif
语句重新分配x。
x = content[0]['OrderItemList'][0]['ItemID']
if x in [2, 3]:
# if x is 2 or 3, set to 5
x = 5
elif x == 4:
x = 2
或者如果您有很多条件可以更改x,请考虑使用dict:
changetos = {2: 5,
3: 5,
#...
}
x = content[0]['OrderItemList'][0]['ItemID']
x = changetos.get(x, x) # if x not in changetos, leave x as is