Home > Enterprise >  how to use fstring in a complex json object
how to use fstring in a complex json object

Time:11-30

Is there a way to use fstring to change variable dynamically in a complex json object like this:

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}"
})

I am trying to change the \"from\": \"2022-11-25T23:59:59\" section, to input a string date variable but running into many problems as the numerous brackets and the embedded strings are making it somewhat difficult when using fstring.

I am also open to any alternative ideas other than fstrings if it fixes the problem

CodePudding user response:

As I suggested, just convert the nested JSON to a dict and manipulate it:

import json

payload = {
   "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}"
}

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

Output:

{"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": "{\"limit\": 10, \"offset\": 0, \"network\": \"ethereum\", \"from\": \"2024-11-25T23:59:59\", \"till\": \"2022-11-28T23:59:59\", \"dateFormat\": \"%Y-%m-%d\"}"}
  • Related