0

How can i cut from such a string (json) everything before and including the first [ and everything behind and including the last ] with 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",
}
...
...
2
  • why are you treating it like a string? Just access that element when you need it Commented Sep 24, 2018 at 14:26
  • You have to parse the JSON to do it safely, so you may as well use json.loads to get an object, extract the desired value, then re-encode it. Commented Sep 24, 2018 at 14:27

4 Answers 4

4

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.

obj = json.loads(data)
relevant_data = obj["Customers"]
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks, but how do to it otherwise?
1

Addition to @Daniel Rosman answer, if you want all the list from JSON.

result = []
obj = json.loads(data)

for value in obj.values():
    if isinstance(value, list):
        result.append(*value)

1 Comment

This is also correct, but due to the question the answer which best fits is Daniels answer.
0

While I agree that Daniel's answer is the absolute best way to go, if you must use string splitting, you can try .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.

Comments

0

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]

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.