To retrieve the values from the JSON file, I use this code:
JavaScript
x
9
1
import json
2
3
json_file = json.load(open('Bla_Bla_Bla.json'))
4
5
master_data = json_file['messages']
6
7
for unique_message in master_data:
8
print(unique_message['text'])
9
This is the JSON template:
JavaScript
1
16
16
1
{
2
"name": "Bla Bla Bla",
3
"type": "public_channel",
4
"id": 123456789,
5
"messages": [
6
{
7
"id": 12460,
8
"type": "message",
9
"date": "2022-02-07T04:14:51",
10
"from": "Bla Bla Bla",
11
"from_id": "channel1127646148",
12
"text": "Yesterday's Tipsn n First Halfn Tips: 2n Win/Loss: 0/2n Void: 0n Win Ratio: 0%n Invested: 2un Net Profit: -2un ROI: -100%n n Second Halfn Tips: 10n Win/Loss: 4/4n Void: 2n Win Ratio: 40%n Invested: 8un Net Profit: 1.145un ROI: 14.3%n n Totaln Tips: 12n Win/Loss: 4/6n Void: 2n Win Ratio: 33.3%n Invested: 10un Net Profit: -0.855un ROI: -8.6%n n Highest Odds won: 2.500"
13
}
14
]
15
}
16
This is the output text:
JavaScript
1
31
31
1
Yesterday's Tips
2
3
First Half
4
Tips: 2
5
Win/Loss: 0/2
6
Void: 0
7
Win Ratio: 0%
8
Invested: 2u
9
Net Profit: -2u
10
ROI: -100%
11
12
Second Half
13
Tips: 10
14
Win/Loss: 4/4
15
Void: 2
16
Win Ratio: 40%
17
Invested: 8u
18
Net Profit: 1.145u
19
ROI: 14.3%
20
21
Total
22
Tips: 12
23
Win/Loss: 4/6
24
Void: 2
25
Win Ratio: 33.3%
26
Invested: 10u
27
Net Profit: -0.855u
28
ROI: -8.6%
29
30
Highest Odds won: 2.500
31
I’m trying to collect the value to Net Profit:
that is inserted inside Total
, the texts can change and the positions too, but whenever there is a Total
, there will be a Net Profit:
.
The value I want to collect in this case is:
JavaScript
1
2
1
-0.855u
2
How can I go about getting that specific part of the text value?
Advertisement
Answer
For more complex cases, you may want to look into Regular Expressions (Regex), but for this simple case:
JavaScript
1
7
1
string = unique_message["text"] # the json data
2
3
string = string[string.find("Total"):] # cut all the part before "Total"
4
string = string[string.find("Net Profit") + 12:] # cut all the part before "Net Profit" (the + 12 removes the Net Profit bit too)
5
string = string[:string.find("n")] # take the part of the string till the next line
6
print(string)
7
Here, we use the str.find()
function which returns the index of a certain part of a string together with string slicing string[start:end]
to find only the part of the string needed. The n
is a special character which denotes the end of a line.