Scala中如何替换字符串列的\"为"以格式化JSON
处理嵌套JSON字符串的转义问题
我有一列格式混乱的嵌套JSON字符串,希望通过regexp_replace编辑后能被Scala解析为struct类型。该JSON中每个元素都被随机添加了\",需要将其替换为"。我已通过regexp_replace移除了\n,但替换\"时遇到问题,尝试用\\\和"""作为转义字符均无效。
示例JSON
{ {"id": "1", "json": [ { \"details\": {\n \"name\" : \"john\", \n \"lastname\" : \"doe\"\ \n}, \"location\": {\n \"city\" : \"new york\", \n \"country\" : \"usa\" \n} }, { \"details\": {\n \"name\" : \"jane\", \n \"lastname\" : \"random\"\ \n}, \"location\": {\n \"city\" : \"new york\", \n \"country\" : \"usa\" \n} }, ] }, {"id": "2", "json": [ { \"details\": {\n \"name\" : \"jack\", \n \"lastname\" : \"ryan\"\ \n}, \"location\": {\n \"city\" : \"york\", \n \"country\" : \"uk\" \n} }, { \"details\": {\n \"name\" : \"jill\", \n \"lastname\" : \"test\"\ \n}, \"location\": {\n \"city\" : \"LA\", \n \"country\" : \"usa\" \n} }, ] } }
现有处理代码
var newdf = df.withcolumn( "clean_json", regexp_replace(regexp_replace(col("json"), "\n", ""), """\"""", "\\\""))
解决方案
正确的转义替换代码
由于Scala字符串和正则表达式存在双重转义要求,要匹配\"需要使用正确的转义序列:
var newdf = df.withColumn("clean_json", regexp_replace( regexp_replace(col("json"), "\n", ""), "\\\\"", // 匹配原字符串中的 \" """ // 替换为 " ) )
特殊情况说明
如果你的JSON中实际存在的是\"(而非显示的\"),则需要调整匹配和替换的字符串:
var newdf = df.withColumn("clean_json", regexp_replace( regexp_replace(col("json"), "\n", ""), "\\\\\"", // 匹配原字符串中的 \" "\"" // 替换为 " ) )
内容的提问来源于stack exchange,提问作者P201_eng
相关产品推荐
相关产品推荐

