json - 在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":"**************"
]
]
}
]
}
解决方案
不使用 UDF 试试这个:
import pyspark.sql.functions as F
df2 = df.withColumn(
'response',
F.concat(
F.lit("{\"analyzedContent\": {"),
F.to_json(F.col("entities")),
F.lit("}}")
)
)
推荐阅读
- linux - 如何覆盖来自kafka消费者的csv中的数据
- ontology - 如何使用 owlapi 确定最不常见的子消费者
- reactjs - 是否需要在 useEffect 返回挂钩中将 useState 设置为其默认值?
- postgresql - 为什么天数在 Postgresql 中不起作用?
- javascript - 如何使用 Dynamics 365 中的 JS 在子网格中循环行(当前行除外)
- vue.js - 如何将tailwindcss添加到vite?
- docker - Docker-Compose up 命令出现“找不到目录”错误
- python - Pyttsx3 之前工作过,但现在不行
- mysql - 如何在 vb.net 中为同一列添加两个案例来操作 mysql 中的数据?
- ringcentral - 在engage.ringcentral.com/voice 的API 响应中,“Jwt 缺失”指的是什么?