[英]How to remove the first and last portion of a string in Python?
How can i cut from such a string (json) everything before and including the first [
and everything behind and including the last ]
with Python? 如何使用Python从这样的字符串(json)剪切掉所有内容,包括Python之前的所有内容,以及第一个 [
以及后面的所有内容,包括最后一个 ]
?
{
"Customers": [
{
"cID": "w2-502952",
"soldToId": "34124"
},
...
...
],
"status": {
"success": true,
"message": "Customers: 560",
"ErrorCode": ""
}
}
I want to have at least only 我至少要
{
"cID" : "w2-502952",
"soldToId" : "34124",
}
...
...
String manipulation is not the way to do this. 字符串操作不是这样做的方法。 You should parse your JSON into Python and extract the relevant data using normal data structure access. 您应该将JSON解析为Python,并使用常规数据结构访问权限提取相关数据。
obj = json.loads(data)
relevant_data = obj["Customers"]
Addition to @Daniel Rosman answer, if you want all the list
from JSON
. 如果您要从JSON
所有list
,请添加@Daniel Rosman答案。
result = []
obj = json.loads(data)
for value in obj.values():
if isinstance(value, list):
result.append(*value)
If you really want to do this via string manipulation (which I don't recommend), you can do it this way: 如果您真的想通过字符串操作(我不建议这样做),可以这样:
start = s.find('[') + 1
finish = s.find(']')
inner = s[start : finish]
While I agree that Daniel's answer is the absolute best way to go, if you must use string splitting, you can try .find()
虽然我同意丹尼尔(Daniel)的回答是绝对最佳的方法,但如果必须使用字符串拆分,则可以尝试.find()
string = #however you are loading this json text into a string
start = string.find('[')
end = string.find(']')
customers = string[start:end]
print(customers)
output will be everything between the [
and ]
braces. 输出将是[
和]
大括号之间的所有内容。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.