Skip to content

Instantly share code, notes, and snippets.

@sinebeef
Last active March 27, 2019 11:27
Show Gist options
  • Save sinebeef/fbc1b3232709368cd3558da103e54cd7 to your computer and use it in GitHub Desktop.
Save sinebeef/fbc1b3232709368cd3558da103e54cd7 to your computer and use it in GitHub Desktop.
'''
parsing CSV into a JSON file using SKU as primary key but also as SKU.
If price is 0 then it must be disabled by putting stock to 0 as well
If weight is 0 then it must also be put to stock 0 to avoid breaking
of the weights based shipping. this will process a json file which can
be used by wpallimport to update existing woocommerce products
@date 20190320
@url https://gist.github.com/sinebeef/fbc1b3232709368cd3558da103e54cd7
'''
import re, csv, json, time
def randFile():
a = 'saved_json_' + str(time.time()).split('.')[0] + '.json'
return a
data = []
with open('20190320_js_products_1125.csv', 'r', newline='') as csv_file:
csv_reader = csv.DictReader(csv_file, delimiter=',')
line_count = 0
for row in csv_reader:
if line_count == 0:
line_count += 1
else:
moo = {}
moo['sku'] = row['sku']
# If price is null or empty make 0
if not row['price'] or row['price'] == 'NULL':
print('There is a null price...')
row_price = float(0)
else:
row_price = float(row['price'])
moo['price'] = row_price
# if price is 0 then make no stock
# so purchase is not possible
if row_price == 0 or row_price == float(0):
row_stock = 0
else:
row_stock = 69
moo['stock'] = row_stock
# If there is no weight, make it stock 0 so product
# cannot be purchased for free
row_weight_value = 0
if not row['weight'] or row['weight'] == 'NULL':
row_weight_value = 0
else:
try:
row_weight_value = int(round(float(row['weight'])))
except:
print(row['sku'] + ' ' + row['weight'])
pass
if row_weight_value == 0:
moo['stock'] = 0
moo['weight'] = row_weight_value
# update list with dicts
data.append(moo)
with open( randFile(),"w") as w:
json.dump(data, w)
w.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment