首页 > 解决方案 > 在pyspark中将JSON对象数组转换为字符串

问题描述

我有一个要求,我需要从一个 PySpark 数据帧返回的列中创建一个自定义 JSON。所以我写了一个像下面这样的 UDF,它将为每一行从 UDF 返回一个字符串格式的 JSON。

参数“entities”是 JSON 格式的数组。

def halResponse(entities, admantx, copilot_id): 
  json_resp = "{\"analyzedContent\": {"+json.dumps(entities)+"}}"
  return json_resp

但在响应中,我没有得到正确的 JSON 即而不是正确的键:值对,我只是得到值(实际值替换为 * 出于安全目的),而不是键和值。

查找示例响应:

  "analyzedContents": [
    {
      "entities": [
        [
          "******",
          *,
          *********,
          [
            [
              "***********",
              "***********",
              "***********",
              [
                "*****************"
              ],
              **********
            ]
          ],
          "**************"
        ]
      ]
    }
  ]
}

请帮我解决这个问题。修复后,我应该得到以下示例响应

  "analyzedContents": [
    {
      "entities": [
        [
          "key":******",
          "key":*,
          "key":*********,
          [
            [
              "key":"***********",
              "key":"***********",
              "key":"***********",
              [
                "key":"*****************"
              ],
              "key":**********
            ]
          ],
          "key":"**************"
        ]
      ]
    }
  ]
}

标签: jsonapache-sparkpysparkapache-spark-sql

解决方案


不使用 UDF 试试这个:

import pyspark.sql.functions as F

df2 = df.withColumn(
    'response',
    F.concat(
        F.lit("{\"analyzedContent\": {"),
        F.to_json(F.col("entities")),
        F.lit("}}")
    )
)

推荐阅读