Reputation: 575
----------------------- UPDATED ----------------------
Since there was so much confusion, I decided to give a more detailed explanation. Take a look at the code below, and focus on
day = {"days": buildString2(day_array[i])}
Here is the code:
import csv, sys, requests, json, os, itertools, ast
def buildString(item):
item_array = item.split(",")
mod = []
for i in range(len(item_array)):
mod.append("%s" % item_array[i].strip())
return mod
def buildString2(item):
item_array = item.split(",")
mod = "["
for i in range(len(item_array)):
if i == len(item_array) - 1:
mod = mod + '%s' % item_array[i].strip()
else:
mod = mod + '%s, ' % item_array[i].strip()
mod = mod + "]"
return mod
if __name__ == '__main__':
def main():
filename = 'file.csv'
dict = {"id":'c8d5185667f'}
with open(filename, 'r', encoding='utf8') as f:
reader = csv.reader(f)
try:
count = 0
for row in reader:
count = count + 1
if count != 1:
dict["name"] = row[10]
dict["space_usages"] = buildString(row[19])
availablle_array = []
available_booking_hours = row[15]
days = row[18]
availability_array = available_booking_hours.split("*")
day_array = days.split("*")
for i in range(len(day_array)):
startEndTime = availability_array[i].split("-")
day = {"days": buildString2(day_array[i])}
times = {"start_time":startEndTime[0], "end_time":startEndTime[1]}
day["times"] = times
availablle_array.append(day)
dict["available_days"] = availablle_array
print(dict)
url = 'http://50.97.247.68:9000/api/v1/spaces'
response = requests.post(url, data=json.dumps(dict))
When I print dict, I get the following
{'id': 'c8d5185667f', 'available_days': [{'days': '[true, true, true, true, true, true, true]', 'times': {'start_time': '12:00', 'end_time': '10:00'}}], 'space_usages': ['Fitness', 'Events', 'Classes', 'Performance']}
but my boss wants this
{'id': 'c8d5185667f', 'available_days': [{'days': [true, true, true, true, true, true, true], 'times': {'start_time': '12:00', 'end_time': '10:00'}}], 'space_usages': ['Fitness', 'Events', 'Classes', 'Performance']}
this doesn't work either
{'id': 'c8d5185667f', 'available_days': [{'days': ['true', 'true', 'true', 'true', 'true', 'true', 'true'], 'times': {'start_time': '12:00', 'end_time': '10:00'}}], 'space_usages': ['Fitness', 'Events', 'Classes', 'Performance']}
Does this make more sense? Is it possible to get
[true, true, true, true, true, true, true]
as a value? I tried doing this
day = {"days": ast.literal_eval(buildString2(day_array[i]))}
but it crashes. I'm out of ideas. I've tried googling a variety of things, and I can't seem to find anything. Your help is greatly appreciated. I honestly don't believe this is possible, but that's what I've been told to do.
NOTE: They have to be lowercase. This doesn't work
[True, True, True, True, True, True, True]
Upvotes: 0
Views: 4677
Reputation: 279455
It's possible to get what your boss wants, just not using the built-in True and False:
class MyBool(object):
def __init__(self, value):
self.value = bool(value)
def __repr__(self):
return repr(self.value).lower()
def __bool__(self):
return self.value
print({'a' : [MyBool(True), MyBool(True), MyBool(False)]})
Result:
{'a': [true, true, false]}
You don't actually need __bool__
, but (in Python 3) it allows the objects to be used in logical conditions.
So as requested, it's not a valid Python literal since it uses true
instead of True
, and it's not valid JSON since it uses single-quoted key strings instead of double-quoted. Presumably it's parsed by something that doesn't accept True
and also doesn't accept double-quoted strings? I don't suppose there's any chance of just fixing the original API to accept JSON?
Upvotes: 0
Reputation: 21329
Your value is
week = '[true, false, true, false, true, false, true]'
Which is JSON representation. Second value is
week = ['true', 'false', 'true', 'false', 'true', 'false', 'true']
Which is List with "true" and "false" strings.
week = [True, False, True, False, True, False, True]
Which is pure python code.
You have to decide which value you have and which way you have to select to convert it in which form.
For first value you can use json.loads
.
For second value you have to check manually string for "true" and "false"
Third is python only so no need to change it in python again :).
Upvotes: 0
Reputation: 36181
You can use the json
module to convert your boolean list to a string and reciprocally:
>>> import json
>>> json.dumps([True, False, True, True, False])
'[true, false, true, true, false]'
>>> json.loads('[true, false, true, true, false]')
[True, False, True, True, False]
Upvotes: 2
Reputation: 1025
This is JSON, so you should just convert your week into JSON format
In [1]: import simplejson as json
In [2]: week = [True, False, True, True]
In [3]: json.dumps(week)
Out[3]: '[true, false, true, true]'
To convert back, just load and parse it:
In [8]: print json.loads('[true, false, false, true]')
[True, False, False, True]
Upvotes: 4