Reputation: 3502
If I have Json data that looks like this:
import json
rawData= {
"Date": "2020-08-16T13:37:22.501743", "MeterReading": 199
}
jsonData = json.dumps(rawData)
print(jsonData)
In Python how could I create a boolean statement to know if the Json object contains only string Date
and MeterReading
? If I use this...
mystring = "MeterReading Date"
for key in jsonData:
if key in mystring:
print('yes')
else:
print('no')
this will print something unwanted as shown below. Ideally if the Json object contains Date
and a timestampt, as well as MeterReading
to contains some sort of float or int value. Any tips greatly appreciated...
no
no
yes
yes
yes
yes
no
no
yes
no
no
no
no
no
no
no
no
no
no
no
no
no
no
no
no
no
no
no
no
no
no
no
no
no
no
no
no
no
yes
no
yes
yes
yes
yes
yes
yes
yes
yes
yes
yes
yes
yes
no
no
no
yes
no
no
no
no
Upvotes: 1
Views: 45
Reputation: 78700
Operate on the dict directly. json.load
or json.loads
it if necessary.
Then use the fact that in many ways dict keys behave like sets:
>>> rawData.keys() == {'Date', 'MeterReading'}
True
Upvotes: 2
Reputation: 531355
String iteration is done character-by-character, not by space-separated word. You need to split myString
first (or use a list in the first place):
mystring = "MeterReading Date"
mywords = mystring.split()
for key in jsonData:
if key in mywords:
print('yes')
else:
print('no')
Upvotes: 0