我有一个从csv文件生成的json对象:
{"FID":["FID"],"the_geom":["the_geom"],"X":["X"],"Y":["Y"],"ROW":["ROW"],"COL":["COL"],"EMH":["EMH"],"B":["B_SURF","B_SUB1","B_SUB2"],"BP_CA":["BP_CA_SUR","BP_CA_SUB1","BP_CA_SUB2"],"BP_K":["BP_K_SURF","BP_K_SUB1","BP_K_SUB2"],"BP_MG"["BP_MG_SUR","BP_MG_SUB1","BP_MG_SUB2"],"BP_NA":["BP_NA_SUR","BP_NA_SUB1","BP_NA_SUB2"],"CA"["CA_SURF","CA_SUB1","CA_SUB2"],"CAMG":["CAMG_SURF","CAMG_SUB1","CAMG_SUB2"],"CEC"["CEC_SURF","CEC_SUB1","CEC_SUB2"],"CLAY":["CLAY_SURF","CLAY_SUB1","CLAY_SUB2"],"CU"["CU_SURF","CU_SUB1","CU_SUB2"],"DPRR_SUMM":["DPRR_SUMM"],"DRAIN_SUMM"["DRAIN_SUMM"],"FE":["FE_SURF","FE_SUB1","FE_SUB2"],"K"["K_SURF","K_SUB1","K_SUB2"],"KMG":["KMG_SURF","KMG_SUB1","KMG_SUB2"],"MG"["MG_SURF","MG_SUB1","MG_SUB2"],"MN":["MN_SURF","MN_SUB1","MN_SUB2"],"NA":["NA_SURF","NA_SUB1","NA_SUB2"],"OM":["OM_SURF","OM_SUB1","OM_SUB2"],"P"["P_SURF","P_SUB1","P_SUB2"],"PAVL"["PAVL_SURF","PAVL_SUB1","PAVL_SUB2"],"PAW24_SUMM":["PAW24_SUMM"],"PAW30_SUMM"["PAW30_SUMM"],"PAW36_SUMM":["PAW36_SUMM"],"PAW42_SUMM":["PAW42_SUMM"],"PAW48_SUMM":["PAW48_SUMM"],"PH":["PH_SURF","PH_SUB1","PH_SUB2"],"RZFC_SUMM":["RZFC_SUMM"],"RZKUSAT_SU"["RZKUSAT_SU"],"RZPAW_SUMM":["RZPAW_SUMM"],"RZPWP_SUMM"["RZPWP_SUMM"],"RZSAT_SUMM":["RZSAT_SUMM"],"S":["S_SURF","S_SUB1","S_SUB2"],"SAND":["SAND_SURF","SAND_SUB1","SAND_SUB2"],"TEX"["TEX_SURF","TEX_SUB1","TEX_SUB2"],"THICK"["THICK_SURF","THICK_SUB1","THICK_SUB2"],"TIP":["TIP_SURF","TIP_SUB1","TIP_SUB2"],"ZN":["ZN_SURF","ZN_SUB1","ZN_SUB2"],"EMV"["EMV"],"ASP":["ASP"],"DEM":["DEM"],"SLOPE\r":["SLOPE\r"]}
最后,斜坡对象在名称中有一个回车符(它是从csv转换中转移的)
我需要从对象中删除回车符,因为它会弄乱一些解析对象的其他脚本。
我尝试通过以下方式进行测试:
console.log("Without carrage return: " + JSON.stringify(jsonObject).replace(/[\n\r]/g, ''));
但是当我打印它时,它仍然包含回车符。
我可能在这里做了些蠢事,我感到很累,我没有注意到它。
感谢任何帮助,谢谢!
答案 0 :(得分:3)
你的正则表达式有点破碎。因为\也是一个特殊的角色,你也需要对它进行区分。
尝试这样做:
console.log("Without carrage return: " + JSON.stringify(jsonObject).replace(/[\\n\\r]/g, ''));
你的正则表达式与\ r \ n字符整体匹配,但由于你将所有内容都转换为字符串,你最终必须匹配字符' \'和' r'。
答案 1 :(得分:1)
csv中的\ r \ n字面意思是反斜杠和r?
console.log( JSON.stringify(jsonObject).replace("\\r", "") )
答案 2 :(得分:0)
在正则表达式\r
和\n
匹配回车符和新行,但JSON.stringify()
将回车符转换为'\r'
。
因此,您只需使用\\r
代替\r
:
console.log("Without carrage return: " + JSON.stringify(jsonObject).replace(/\\n|\\r/g, ''));
编辑:/[\\n\\r]/g
将匹配字符串中的每个反斜杠和每个字母r和n,而不仅仅是序列\ r \ n。 /\\n|\\r/g
效果更好。