簡體   English   中英

從字符串中動態刪除 substring

[英]Dynamically remove substring from string

我有一個有點直截了當的困境,但我一直無法找到解決方案。

我從 MongoDB 數據庫中獲取 JSON 文件並使用json.dumps將其轉換為字符串:

client = MongoClient("XXXX")
db = client.testdb
table = db.testingtable
document = table.find()
document = list(document)
docs = json.dumps(document,default=str)
print(docs)

當前 Output:

[{"_id": "67", "userId": 167, "productID": "Reference('product_id', ObjectId('5f4523b893d7b757bcbd2d71'))"}]

我將如何 go 關於動態搜索整個字符串以查找Reference一詞,如果找到,它應該刪除括號內除字母數字值之外的所有內容,而不執行此操作:

docs.replace("Reference('product_id', ObjectId('",'').replace("'))",'')

預期 Output:

[{"_id": "67", "userId": 167, "productID": "5f4523b893d7b757bcbd2d71"}]
from pandas.io.json import json_normalize
df=pd.json_normalize([{"_id": "67", "userId": 167, "productID": "Reference('product_id', ObjectId('5f4523b893d7b757bcbd2d71'))"}])#convert to df


#Using regex, extract string between `ObjectId(`and  `)` and turn it back to json
df.assign(productID=df.productID.str.extract('(?<=ObjectId\()(.*?)(?=\))')).to_json(orient="records")


[{"_id":"67","userId":167,"productID":"'5f4523b893d7b757bcbd2d71'"}]

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM