【问题标题】:Assign variable value in JSON payload fomat以 JSON 有效负载格式分配变量值
【发布时间】:2021-12-29 18:37:49
【问题描述】:

我正在使用 python 3.6.3a。我想为每个 json 记录生成有效负载。我正在使用每个变量来访问记录。如何在有效负载中分配变量值(在这种情况下为each)?我尝试了{each} 和其他方法,但没有奏效。

下面的代码 sn-p。

json_records =  [{"description":"<p>This is scenario1<\/p>","owner":"deb",
                  "priority":"high"},
                 {"description":"<p>This is scenario2<\/p>","owner":"deb",
                  "priority":"medium"}]

json_object = json.loads(json_records)

for each in json_object:
   payload = """
   {
     "subject": "test",
     "fieldValues": [
         {each}
      ]
   }
   """

【问题讨论】:

  • 你需要一个集合,比如一个列表
  • 类似的,如果不是完全重复的话:stackoverflow.com/q/70513374/1126841。请注意,您的列表 json_records 根本不是 JSON。它只是 Python dict 对象的列表。
  • 我尝试了链接中提到的方法,它成功了!非常感谢!

标签: python json python-3.x


【解决方案1】:

有两种方法可以解决这个问题。 一种方法是创建一个dict() 对象并根据需要插入键,然后json.dumps(object) 转换为字符串有效负载,如下所示:

import json
json_records = [{"description":"This is scenario1</p>","owner":"deb","priority":"high"}
,{"description":"This is scenario2</p>","owner":"deb","priority":"medium"}]

for obj in json_records:
    payload =  dict()
    payload['subject'] = 'test'
    for key,value in obj.items():
        payload['fieldName'] = {
            key:value
        }
    print(json.dumps(payload))
#{"subject": "test", "fieldName": {"priority": "high"}}
#{"subject": "test", "fieldName": {"priority": "medium"}}

第二种方法是从字符串创建一个文本有效负载,但是如果您最后需要一个有效的 JSON,这将需要验证的后期步骤(类似于try json.loads(payload) - 所以我只是使用第一种方法。仅当我有特定要求以某种方式生成有效负载时,我才会使用此方法。

import json
json_records = [{"description":"This is scenario1</p>","owner":"deb","priority":"high"}
,{"description":"This is scenario2</p>","owner":"deb","priority":"medium"}]

# json_object = json.loads(json_records) # json.loads works only on byte-like strings. your object is already in python in this case.

for obj in json_records:
    payload =  """
   {
     "subject": "test",
     "fieldValues": [ 
         %s 
      ]
   }
   """ % (obj["priority"])
    print(payload)
#{
#     "subject": "test",
#     "fieldValues": [ 
#         high 
#      ]
#   }
#   
#
#   {
#     "subject": "test",
#     "fieldValues": [ 
#         medium 
#      ]
#   }
 

【讨论】:

  • 字符串格式操作不保证有效的 JSON。
  • 我同意。不确定 OP 想要达到什么目标。
【解决方案2】:

您可以将payload 设为Template 字符串,并使用它将每个JSON 记录中的数据转换为您想要的格式。括号{} 字符在Templates 中没有特殊含义,这使得它们使用起来很容易。

这样做将创建包含所有内容的字典的有效字符串表示。您可以使用 ast.literal_eval() 函数将其转换为实际的 Python 字典数据结构,然后将 that 转换为 JSON 字符串格式 — 我认为这是您所追求的最终格式。

rom ast import literal_eval
import json
from string import Template
from textwrap import dedent


json_records = '''[{"description":"<p>This is scenario1<\/p>","owner":"deb",
                    "priority":"high"},
                    {"description":"<p>This is scenario2<\/p>","owner":"deb",
                     "priority":"medium"}]'''

json_object = json.loads(json_records)

payload = Template(dedent("""
    {
      "subject": "test",
      "fieldValues": [
          $each
       ]
    }""")
)

for each in json_object:
    obj = literal_eval(payload.substitute(dict(each=each)))
    print(json.dumps(obj, indent=2))

输出:

{
  "subject": "test",
  "fieldValues": [
    {
      "description": "<p>This is scenario1</p>",
      "owner": "deb",
      "priority": "high"
    }
  ]
}
{
  "subject": "test",
  "fieldValues": [
    {
      "description": "<p>This is scenario2</p>",
      "owner": "deb",
      "priority": "medium"
    }
  ]
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-06-14
    • 2019-12-30
    • 1970-01-01
    • 2018-09-17
    • 2022-07-22
    • 1970-01-01
    • 2019-12-02
    相关资源
    最近更新 更多