【问题标题】:Using python f-string in a json list of data在 json 数据列表中使用 python f-string
【发布时间】:2021-02-21 22:58:18
【问题描述】:

我需要通过他们的 API 将数据推送到网站,我正在尝试找到一种方法来使用 F-string 来传递数据列表中的变量,但找不到方法。

这是我迄今为止尝试过的:

today = datetime.date.today()
tomorrow = today + datetime.timedelta(days = 1)

#trying to pass *tomorrow* value with f-string below

data = f'[{"date": "{tomorrow}", "price": {"amount": 15100}}]'

response = requests.put('https://api.platform.io/calendar/28528204', headers=headers, data=data)

我怎样才能做到这一点?

【问题讨论】:

  • data 可以是字典。
  • @BrownieInMotion 这是什么意思?
  • 您应该使用{{ 来表示f-strings 中的文字{,但@BrownieInMotion 是正确的;您应该直接使用数据结构:data = [{"date": tomorrow, "price": {"amount": 15100}}]requests.put 将自动使用它,但如果您必须将其转换为 json,请使用 json.dumps(data)。不要自己构造 json 字符串,始终使用json 模块。

标签: python json list f-string


【解决方案1】:

我个人会做这样的事情:

import json
import datetime

today = datetime.date.today()
tomorrow = today + datetime.timedelta(days = 1)

data = [{
    "date": str(tomorrow),
    "price": {
        "amount": 15100
    }
}]

print(json.dumps(data))

当然,在此之后,您可以使用json.dumps(data) 做任何您想做的事情:在您的情况下,将其发送到请求中。

【讨论】:

  • 非常感谢值正确传递但我现在收到 400 错误和语法错误?
  • @locq 这似乎是特定于端点的。你能举一个不给出语法错误的请求的例子吗?
  • 数据只在加单引号时有效:data = '[{"date": "2020-11-12", "price": {"amount": 7700}}]'
  • @locq 你能用字符串data = '[{"date": "2020-11-10", "price": {"amount": 15100}}]'试试吗?
  • 是的,这行得通,但现在我需要明天在那里传递变量
猜你喜欢
  • 2023-01-03
  • 1970-01-01
  • 1970-01-01
  • 2022-10-12
  • 2022-01-24
  • 1970-01-01
  • 1970-01-01
  • 2018-08-26
  • 1970-01-01
相关资源
最近更新 更多