【问题标题】:how to use fstring in a complex json object如何在复杂的 json 对象中使用 fstring
【发布时间】:2022-11-29 14:37:20
【问题描述】:

有没有办法使用 fstring 在复杂的 json 对象中动态更改变量,如下所示:

payload = json.dumps({
   "query": "query ($network: EthereumNetwork!, $dateFormat: String!, $from: ISO8601DateTime, $till: ISO8601DateTime) {\n  ethereum(network: $network) {\n    transactions(options: {asc: \"date.date\"}, date: {since: $from, till: $till}) {\n      date: date {\n        date(format: $dateFormat)\n      }\n      count: countBigInt\n      gasValue\n    }\n  }\n}\n",
   "variables": "{\n  \"limit\": 10,\n  \"offset\": 0,\n  \"network\": \"ethereum\",\n  \"from\": \"2022-11-25T23:59:59\",\"till\":\"2022-11-28T23:59:59\",\n  \"dateFormat\": \"%Y-%m-%d\"\n}"
})

我正在尝试更改 \"from\": \"2022-11-25T23:59:59\" 部分,以输入一个字符串日期变量,但遇到了很多问题,因为大量的括号和嵌入的字符串在使用 fstring 时有些困难。

如果它能解决问题,我也愿意接受除 fstrings 之外的任何其他想法

【问题讨论】:

  • variables 本身就是一个嵌套的 JSON 对象。只需使用 json.loads 将其转换为 Python 字典,然后调整字典,然后使用 json.dumps 将其再次转换回来。
  • 是的,可以使用 f-string 执行此操作,但由于您描述的问题,这是不明智的。很难让 f 字符串中的所有括号、斜杠、引号等都正确。正如@TimRoberts 建议的那样,使用为此目的设计的工具。
  • 首先,用单引号而不是双引号将字符串括起来,以消除这些丑陋的转义引号。然后保留所有内容,选择日期字符串 (2022-...-:59) 并将其替换为 {my_date_string}。如果您有 datetime 对象而不是字符串,则可以使用 {my_datetime:%Y-%m-%dT%H%M%S} 或 {my_datetime.isoformat(timespec="minutes")}。最后,在字符串中添加 f 前缀。但是,如果可能,应该首选 json 模块。

标签: python json variables f-string


【解决方案1】:

正如我所建议的,只需将嵌套的 JSON 转换为字典并对其进行操作:

import json

payload = {
   "query": "query ($network: EthereumNetwork!, $dateFormat: String!, $from: ISO8601DateTime, $till: ISO8601DateTime) {
  ethereum(network: $network) {
    transactions(options: {asc: "date.date"}, date: {since: $from, till: $till}) {
      date: date {
        date(format: $dateFormat)
      }
      count: countBigInt
      gasValue
    }
  }
}
",
   "variables": "{
  "limit": 10,
  "offset": 0,
  "network": "ethereum",
  "from": "2022-11-25T23:59:59","till":"2022-11-28T23:59:59",
  "dateFormat": "%Y-%m-%d"
}"
}

var = json.loads(payload['variables'])
var['from'] = var['from'].replace('2022','2024')
payload['variables'] = json.dumps(var)
print(json.dumps(payload))

输出:

{"query": "query ($network: EthereumNetwork!, $dateFormat: String!, $from: ISO8601DateTime, $till: ISO8601DateTime) {
  ethereum(network: $network) {
    transactions(options: {asc: "date.date"}, date: {since: $from, till: $till}) {
      date: date {
        date(format: $dateFormat)
      }
      count: countBigInt
      gasValue
    }
  }
}
", "variables": "{"limit": 10, "offset": 0, "network": "ethereum", "from": "2024-11-25T23:59:59", "till": "2022-11-28T23:59:59", "dateFormat": "%Y-%m-%d"}"}

【讨论】:

    猜你喜欢
    • 2016-09-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    • 1970-01-01
    • 2017-09-09
    • 2016-12-29
    • 2020-04-25
    相关资源
    最近更新 更多