解析复杂的 JSON 在 Airflow 中使用 Python。

huangapple go评论97阅读模式
英文:

Parse complex json in airflow using python

问题

以下是我的JSON。

{
"configuration": [
{
"task_name": "reading",
"novel": {
"name": "ABC",
"author": "aut1"
},
"story": {
"name": "CDE",
"author": "aut2"
}
},
{
"task_name": "singing",
"pop": {
"name": "rockit",
"author": "aut11"
},
"jazz": {
"name": "jazzy",
"author": "aut22"
}
}
]
}

我想从Airflow的管理员变量中读取此JSON,然后根据条件(task_name)进行迭代,并提取值并分配给变量。

由于我是Airflow和Python的新手,所以很难找到答案。欢迎任何输入。

英文:

Below given is my json.

  1. {
  2. "configuration": [
  3. {
  4. "task_name":"reading",
  5. "novel":{
  6. "name":"ABC",
  7. "author":"aut1"
  8. },
  9. "story":{
  10. "name":"CDE",
  11. "author":"aut2"
  12. }
  13. },
  14. {
  15. "task_name":"singing",
  16. "pop":{
  17. "name":"rockit",
  18. "author":"aut11"
  19. },
  20. "jazz":{
  21. "name":"jazzy",
  22. "author":"aut22"
  23. }
  24. }
  25. ]
  26. }

I want to read this json from admin variables in airflow then based on condition(task_name) need to iterate through it and takeout values and assign to variables.

Since i am new in airflow and python it found difficult to get answer.
Welcomes any inputs

答案1

得分: 1

  1. 创建您的管理员变量。将JSON以纯文本形式放入“Val”值中,并指定一个“Key”(例如,“configuration”)。

  2. 在您的Python代码中导入“Variable”模型。

  1. from airflow.models import Variable
  1. 使用“Variable”模型获取您的管理员变量,并将其反序列化为Python的“dict”,将“deserialize_json”设置为“True”。
  1. configs = Variable.get("configuration", deserialize_json=True)
  1. 现在,您可以像普通的“dict”一样进行迭代。
  1. for config in configs["configuration"]:
  2. print(config["task_name"])
英文:

Follow these steps:

  1. Create your admin variable. Put your JSON in plain text in the Val value and specify a Key (e.g. "configuration").
  2. Import the Variable model in your Python code.
  1. from airflow.models import Variable
  1. Get your admin var using the Variable model and deserialize it to a Python dict setting deserialize_json to True.
  1. configs = Variable.get("configuration", deserialize_json=True)
  1. Now you can iterate it like a regular dict.
  1. for config in configs["configuration"]:
  2. print(config["task_name"])

huangapple
  • 本文由 发表于 2023年3月9日 20:37:10
  • 转载请务必保留本文链接:https://go.coder-hub.com/75684723.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定