-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathapi_py_mongoDB.py
40 lines (31 loc) · 1.02 KB
/
api_py_mongoDB.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
import requests
import json
import pymongo
from pprint import pprint
myclient = pymongo.MongoClient("mongodb://localhost:27017/")
r = requests.get('https://formulae.brew.sh/api/formula.json')
packages_json = r.json()
packages_str = json.dumps(packages_json, indent = 2)
#Writing to a file (only selected 1 pair):
with open("json.txt", "w") as external_file:
for i in range(1):
names = json.dumps(packages_json[i], indent = 2)
print(names, file=external_file)
external_file.close()
# Loading or Opening the json file
with open('json.txt') as dta:
file = json.load(dta)
#Setting DB & collection:
mydb = myclient['shop']
mycollection = mydb["porducts"]
#Checking whether single row to insert or many rows.
if isinstance(file, list):
mycollection.insert_many(file)
print("insert many")
else:
mycollection.insert_one(file)
print("insert one")
##print out the result using pprint:
select_find = mycollection.find()
for x in select_find:
pprint(x)