I want to implement an array from the received data that will contain objects with the same identifiers.
pool.query('SELECT * FROM columnslist INNER JOIN tableslist ON columnKey = keyTable', (error, result) => {
response.send(result);
});
After executing this code, I get the expected result:
[
{
"id": 1,
"columnOne": "qeqeqq qq wq qw wwqqwdqd",
"columnTwo": "qdqdqdq wdqdqwqwd",
"columnThree": "dqwdq qw qqsvds",
"columnFour": "svsdvsxcvscsv svd ds",
"columnFive": "sdvsdvsdvs ds sdd",
"columnKey": 1,
"keyTable": 1,
"name": "Test"
},
{
"id": 3,
"columnOne": "qdqwdwq",
"columnTwo": "dqdqd",
"columnThree": "qdqdwq",
"columnFour": "wdqwdqwq",
"columnFive": "wdqdqw",
"columnKey": 2,
"keyTable": 2,
"name": "Qqeqeqeq"
},
{
"id": 4,
"columnOne": "qdqwdwq",
"columnTwo": "dqdqd",
"columnThree": "qdqdwq",
"columnFour": "wdqwdqwq",
"columnFive": "wdqdqw",
"columnKey": 2,
"keyTable": 2,
"name": "Qqeqeqeq"
}
]
Tell me how you can implement or process the response to get this result? I need an array to be created in the array, as I wrote earlier, with the same identifiers:
[
[{"keyTable": 1,"name": "Test"...}],
[{"columnKey": 2,"keyTable": 2...}, [{"columnKey": 2,"keyTable": 2...}]
]
Thanks to!
You can typecast objects into an associative array like this
$array = (array) $yourObject;
In your case
$array = (array) $result;
This will help out you
You can use JSON_ARRAYAGG() AND GROUP BY, for your example the query is :
SELECT ALL
columnKey, keyTable,
JSON_ARRAYAGG(JSON_OBJECT(
'id', id,
'columnOne', columnOne,
'columnTwo', columnTwo,
'columnThree', columnThree,
'columnFour', columnFour,
'columnFive', columnFive,
'columnKey', columnKey,
'keyTable', keyTable,
'name', name
)) AS jsonData
FROM columnslist
INNER JOIN tableslist ON columnKey = keyTable
GROUP BY columnKey, keyTable
https://dev.mysql.com/doc/refman/8.0/en/aggregate-functions.html#function_json-arrayagg
Related
I have a heirarchy of tables in a MySQL 5.6 database that I need to query to a JSON format for use by a javascript tree structure.
Just as a test in my flask I did the following for just the top level
def get_all_customers():
response_object = {'status': 'success'}
cnx = mysql.connector.connect(user="", password="", database="", host="localhost", port=3306)
cursor = cnx.cursor()
cursor.execute('SELECT idx, name FROM listcustomers ORDER BY name')
data = []
for idx, name in cursor:
data.append({'id': idx, 'label':name, 'otherProp': "Customer"})
response_object['customers'] = data
return jsonify(response_object)
which returns
[
{ id: 1,
label: "customer 1",
otherProp: "Customer"
},
...
]
But each customer has locations, and each location has areas, and each area has assets, and each asset has projects, and I need to also query them into children of this json object. So, for example, just going one level deeper to locations, I would need something like this -
[
{ id: 1,
label: "customer 1",
otherProp: "Customer",
children: [
{
id: 5,
label: "location 5",
otherProp: "Location"
},
...
]
},
...
]
where in my database listlocatiosn who links to listcustomers via the it's parentCustomerId column. How can I manage this? Eventually this tree will have about 13,000 objects so I know just querying the data and then parsing it with python would be far more inefficient than if I am able to query properly to begin with.
I need read 2 collections data from MongoDB in Python, is there any way to join data in python?
Let's say that we have two collections(tables):
buy_orders
sell_orders
Those tables have the same field 'id_transaction' , and we want to join those tables on this field:
import pymongo
my_client = pymongo.MongoClient('mongodb://localhost:27017/')
my_db = my_client['Orders']
my_collection = my_db['buy_orders']
result = my_collection.aggregate([{
'$lookup' : {'from': 'sell_orders','localField': 'id_transaction','foreignField': 'id_transaction','as': 'results' }
}])
To print results:
for item in result:
print(item)
For more references: MongoDB Docs and PyMongo Docs
Have a look here
from bson.objectid import ObjectId
#the custom_id for reference
custom_id = ObjectId()
#creating user with the role admin
db.users.insert_one({"name": "Boston", "role_id": custom_id})
#Creating role with the custom id
db.roles.insert_one({"_id": custom_id, "name": "Admin")}
#lookup usage
db.users.aggregate([
{
"$lookup":
{
"from": "roles",
"localField": "role_id",
"foreignField": "_id",
"as": "roles"
}
}
])
Two examples for a JSON request. Both examples should have the correct JSON syntax, yet only the second version seems to be translatable to a dictionary.
#doesn't work
string_js3 = """{"employees": [
{
"FNAME":"FTestA",
"LNAME":"LTestA",
"SSN":6668844441
},
{
"FNAME":"FTestB",
"LNAME":"LTestB",
"SSN":6668844442
}
]}
"""
#works
string_js4 = """[
{
"FNAME":"FTestA",
"LNAME":"LTestA",
"SSN":6668844441
},
{
"FNAME":"FTestB",
"LNAME":"LTestB",
"SSN":6668844442
}]
"""
This gives an error, while the same with string_js4 works
L1 = json.loads(string_js3)
print(L1[0]['FNAME'])
So I have 2 questions:
1) Why doesn't the first version work
2) Is there a simple way to make the first version also work?
Both of these strings are valid JSON. Where you are getting stuck is in how you are accessing the resulting data structures.
L1 (from string_js3) is a (nested) dict;
L2 (from string_js4) is a list of dicts.
Walkthrough:
import json
string_js3 = """{
"employees": [{
"FNAME": "FTestA",
"LNAME": "LTestA",
"SSN": 6668844441
},
{
"FNAME": "FTestB",
"LNAME": "LTestB",
"SSN": 6668844442
}
]
}"""
string_js4 = """[{
"FNAME": "FTestA",
"LNAME": "LTestA",
"SSN": 6668844441
},
{
"FNAME": "FTestB",
"LNAME": "LTestB",
"SSN": 6668844442
}
]"""
L1 = json.loads(string_js3)
L2 = json.loads(string_js4)
The resulting objects:
L1
{'employees': [{'FNAME': 'FTestA', 'LNAME': 'LTestA', 'SSN': 6668844441},
{'FNAME': 'FTestB', 'LNAME': 'LTestB', 'SSN': 6668844442}]}
L2
[{'FNAME': 'FTestA', 'LNAME': 'LTestA', 'SSN': 6668844441},
{'FNAME': 'FTestB', 'LNAME': 'LTestB', 'SSN': 6668844442}]
type(L1), type(L2)
(dict, list)
1) Why doesn't the first version work?
Because calling L1[0] is trying to return the value from the key 0, and that key doesn't exist. From the docs, "It is an error to extract a value using a non-existent key." L1 is a dictionary with just one key:
L1.keys()
dict_keys(['employees'])
2) Is there a simple way to make the first version also work?
There are several ways, but it ultimately depends on what your larger problem looks like. I'm going to assume you want to modify the Python code rather than the JSON files/strings themselves. You could do:
L3 = L1['employees'].copy()
You now have a list of dictionaries that resembles L2:
L3
[{'FNAME': 'FTestA', 'LNAME': 'LTestA', 'SSN': 6668844441},
{'FNAME': 'FTestB', 'LNAME': 'LTestB', 'SSN': 6668844442}]
I have received arguments in my mason handler which looks in the following format:
$data = {
'cacheParams' => 0,
'requests' => {
'locationId' => 1,
'uniqueId' => [
'ABC',
'DEF',
'XYZ'
]
}
};
I am able to access the requests by using $data['requests']. How do I access the values stored in requests, i.e. locationId and uniqueId ? I need to use these values to form another JSON in the following way:
my $input = {
stateID => 44,
locationId => requests.locationId,
uniqueId => requests.uniqueId
.
.
.
}
The $data['requests'] object should be an hash in your way. So you can access to the keys like in the following:
$data['requests']->{'locationId'}
$data['requests']->{'uniqueId'}
or
$requests = $data['requests']
$locationId = $requests->{'locationId'}
$uniqueId = $requests->{'uniqueId'}
This seems such a simple task, yet it eludes me...
class ViewAllDogs(webapp2.RequestHandler):
""" Returns an array of json objects representing all dogs. """
def get(self):
query = Dog.query()
results = query.fetch(limit = MAX_DOGS) # 100
aList = []
for match in results:
aList.append({'id': match.id, 'name': match.name,
'owner': match.owner, arrival_date':match.arrival_date})
aList.append({'departure_history':{'departure_date': match.departure_date,
'departed_dog': match.departed_dog}})
self.response.headers['Content-Type'] = 'application/json'
self.response.write(json.dumps(aList))
The above, my best attempt to date, gets me:
[
{
"arrival_date": null,
"id": "a link to self",
"owner": 354773,
"name": "Rover"
},
{
"departure_history": {
"departed_dog": "Jake",
"departure_date": 04/24/2017
}
},
# json array of objects continues...
]
What I'm trying to get is the departure_history nested:
[
{
"id": "a link to self...",
"owner": 354773,
"name": "Rover",
"departure_history": {
"departed_dog": "Jake",
"departure_date": 04/24/2017
},
"arrival_date": 04/25/2017,
},
# json array of objects continues...
]
I've tried a bunch of different combinations, looked at json docs, python27 docs, no joy, and burned about way too many hours with this. I got this far with the many related SO posts on this topic. Thanks in advance.
You can simplify a little:
aList = []
for match in results:
aDog = {'id': match.id,
'name': match.name,
'owner': match.owner,
'arrival_date':match.arrival_date,
'departure_history': {
'departure_date': match.departure_date,
'departed_dog': match.departed_dog}
}
aList.append(aDog)
This seems a bit hackish, but it works. If you know a better way, by all means, let me know. Thanks.
class ViewAllDogs(webapp2.RequestHandler):
""" Returns an array of json objects representing all dogs. """
def get(self):
query = Dog.query()
results = query.fetch(limit = MAX_DOGS) # 100
aList = []
i = 0
for match in results:
aList.append({'id': match.id, 'name': match.name,
'owner': match.owner, arrival_date':match.arrival_date})
aList[i]['departure_history'] = ({'departure_history':{'departure_date': match.departure_date,
'departed_dog': match.departed_dog}})
i += 1
self.response.headers['Content-Type'] = 'application/json'
self.response.write(json.dumps(aList))