Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 2 years ago.
Improve this question
class Order_ListAPIView(APIView):
def get(self,request,format=None):
totalData=[]
if request.method == 'GET':
cur,conn = connection()
order_query = ''' SELECT * FROM orders '''
order_detail_query = ''' SELECT * FROM order_details '''
user_query = ''' SELECT * FROM users '''
with conn.cursor(MySQLdb.cursors.DictCursor) as cursor:
cursor.execute(order_detail_query)
order_detail_result = cursor.fetchall()
order_detail_data = list(order_detail_result)
# print(order_detail_data)
cursor.execute(order_query)
order_result = cursor.fetchall()
order_data = list(order_result)
cursor.execute(user_query)
user_result = cursor.fetchall()
user_data = list(user_result)
dic = {}
def merge_order_data_and_detail(order_data, order_detail_data):
for d in order_detail_data:
if d['order_id'] not in dic:
dic[d['order_id']] = []
dic[d['order_id']].append(d)
for o in order_data:
if o['order_id'] in dic:
o['order_detail_data'] = dic[o['order_id']]
merge_order_data_and_detail(order_data, order_detail_data)
# totalData.append({"order_data":order_data, })
return Response({"order_data":order_data, "user_data":user_data},status=status.HTTP_200_OK)
else:
return Response(status=status.HTTP_400_BAD_REQUEST)
Output:
{
"order_data": [
{
"order_id": 1,
"payment_method_id": 1,
"delivery_id": 2,
"user_id": 3,
"txnid": "584ffb7fd622eca10a6d",
"order_no": "1-1583152683-0005",
"order_total": 1.0,
"payment_status": "Paid",
"payuMoneyId": "306043618",
"mihpayid": "9956109007",
"order_detail_data": [
{
"order_detail_id": 1,
"order_id": 1,
"user_id": 3,
"qty": 1,
"product_price": 1.0,
"order_item_status": "Placed",
"feedback": ""
}
]
},
{
"order_id": 2,
"payment_method_id": 2,
"delivery_id": 2,
"user_id": 2,
"txnid": "",
"order_no": "1-1583152785-0010",
"order_total": 1.0,
"payment_status": "Unpaid",
"payuMoneyId": "",
"mihpayid": "",
"order_detail_data": [
{
"order_detail_id": 2,
"order_id": 2,
"user_id": 2,
"qty": 1,
"product_price": 1.0,
"order_item_status": "Cancelled",
"feedback": "0"
}
]
},
{
"order_id": 3,
"payment_method_id": 1,
"delivery_id": 2,
"user_id": 1,
"txnid": "83e066ca75437f433343d05b0",
"order_no": "2-1583152964-0019",
"order_total": 2.0,
"payment_status": "Paid",
"payuMoneyId": "306044826",
"mihpayid": "9956136979",
"order_detail_data": [
{
"order_detail_id": 3,
"order_id": 3,
"user_id": 1,
"qty": 2,
"product_price": 1.0,
"order_item_status": "Placed",
"feedback": ""
}
]
},
],
"user_data": [
{
"user_id": 1,
"role": 0,
"created_by": 0,
"group_in": 0,
"name": "Deebaco",
"email": "singh.deeba#gmail.com",
"mobile": "",
"password": "",
"image": "",
"last_login": null,
"rand": "",
"opened": 0,
"auth_id": "114025425174039",
"auth_platform": "Google",
"created_datetime": "2020-03-02T17:54:28",
"updated_datetime": "2020-03-02T17:54:28",
"status": "Active"
},
{
"user_id": 2,
"role": 0,
"created_by": 0,
"group_in": 0,
"name": "Kriti Mathur",
"email": "mathurkriti#gmail.com",
"mobile": "",
"password": "",
"image": "",
"last_login": null,
"rand": "",
"opened": 0,
"auth_id": "111445960345755",
"auth_platform": "Google",
"created_datetime": "2020-03-02T18:02:24",
"updated_datetime": "2020-03-02T18:02:24",
"status": "Active"
},
{
"user_id": 3,
"role": 0,
"created_by": 0,
"group_in": 0,
"name": "Sakshi Swarnkar",
"email": "sakshi#gmail.com",
"mobile": "",
"password": "",
"image": "",
"last_login": null,
"rand": "",
"opened": 0,
"auth_id": "117543975857",
"auth_platform": "Google",
"created_datetime": "2020-03-02T18:02:24",
"updated_datetime": "2020-03-02T18:02:24",
"status": "Active"
},
]
}
what i want is like this below: get name replace of user_id.
{
"order_data": [
{
"order_id": 1,
"payment_method_id": 1,
"delivery_id": 2,
"name": "Sakshi Swarnkar",
"txnid": "584ffb7fd622eca10a6d",
"order_no": "1-1583152683-0005",
"order_total": 1.0,
"payment_status": "Paid",
"payuMoneyId": "306043618",
"mihpayid": "9956109007",
"order_detail_data": [
{
"order_detail_id": 1,
"order_id": 1,
"name": "Sakshi Swarnkar",
"qty": 1,
"product_price": 1.0,
"order_item_status": "Placed",
"feedback": ""
}
]
},
{
"order_id": 2,
"payment_method_id": 2,
"delivery_id": 2,
"name": "Kriti Mathur",
"txnid": "",
"order_no": "1-1583152785-0010",
"order_total": 1.0,
"payment_status": "Unpaid",
"payuMoneyId": "",
"mihpayid": "",
"order_detail_data": [
{
"order_detail_id": 2,
"order_id": 2,
"name": "Kriti Mathur",
"qty": 1,
"product_price": 1.0,
"order_item_status": "Cancelled",
"feedback": "0"
}
]
},
{
"order_id": 3,
"payment_method_id": 1,
"delivery_id": 2,
"name": "Deebaco",
"txnid": "83e066ca75437f433343d05b0",
"order_no": "2-1583152964-0019",
"order_total": 2.0,
"payment_status": "Paid",
"payuMoneyId": "306044826",
"mihpayid": "9956136979",
"order_detail_data": [
{
"order_detail_id": 3,
"order_id": 3,
"name": "Deebaco",
"qty": 2,
"product_price": 1.0,
"order_item_status": "Placed",
"feedback": ""
}
]
},
],
i am direct fetching data using raw query from databases instead of
ORM. i want to get user-name replace of user_id.
i am trying to solve this problem, but i didn't get any possible answer which could solve this problem. It would be great if anyone could help me out for what i am looking for. Advance thank you so much!.
You will need to change the sql query of: order_query = ''' SELECT * FROM orders '''
Your sql query will need a join
SELECT users.name,order.* from order left join users on order.user_id = users.user_id
It will not be exactly what you expect because I don't have all the information and I'm making assumptions about your DB, but this should work after you reworked it slightly
Related
I want to merge list of dictionary provided below with unique channel and zrepcode.
sample input:
[
{
"channel": 1,
"zrepcode": "123456",
"turn": 7833.9
},
{
"channel": 1,
"zrepcode": "123456",
"pipeline": 324
},
{
"channel": 1,
"zrepcode": "123456",
"inv_bal": 941.16
},
{
"channel": 1,
"zrepcode": "123456",
"display": 341
},
{
"channel": 3,
"zrepcode": "123456",
"display": 941.16
},
{
"channel": 3,
"zrepcode": "123456",
"turn": 7935.01
},
{
"channel": 3,
"zrepcode": "123456",
"pipeline": 0
},
{
"channel": 3,
"zrepcode": "123456",
"inv_bal": 341
},
{
"channel": 3,
"zrepcode": "789789",
"display": 941.16
},
{
"channel": 3,
"zrepcode": "789789",
"turn": 7935.01
},
{
"channel": 3,
"zrepcode": "789789",
"pipeline": 0
},
{
"channel": 3,
"zrepcode": "789789",
"inv_bal": 341
}
]
Sample output:
[
{'channel': 1, 'zrepcode': '123456', 'turn': 7833.9, 'pipeline': 324.0,'display': 341,'inv_bal': 941.16},
{'channel': 3, 'zrepcode': '123456', 'turn': 7935.01, 'pipeline': 0.0, 'display': 941.16, 'inv_bal': 341.0},
{'channel': 3, 'zrepcode': '789789', 'turn': 7935.01, 'pipeline': 0.0, 'display': 941.16, 'inv_bal': 341.0}
]
Easily solved with our good friend collections.defaultdict:
import collections
by_key = collections.defaultdict(dict)
for datum in data: # data is the list of dicts from the post
key = (datum.get("channel"), datum.get("zrepcode")) # form the key tuple
by_key[key].update(datum) # update the defaultdict by the key tuple
print(list(by_key.values()))
This outputs
[
{'channel': 1, 'zrepcode': '123456', 'turn': 7833.9, 'pipeline': 324, 'inv_bal': 941.16, 'display': 341},
{'channel': 3, 'zrepcode': '123456', 'display': 941.16, 'turn': 7935.01, 'pipeline': 0, 'inv_bal': 341},
{'channel': 3, 'zrepcode': '789789', 'display': 941.16, 'turn': 7935.01, 'pipeline': 0, 'inv_bal': 341},
]
class Order_ListAPIView(APIView):
def get(self,request,format=None):
totalData=[]
if request.method == 'GET':
cur,conn = connection()
order_query = ''' SELECT * FROM orders'''
order_detail_query = ''' SELECT * FROM order_details'''
with conn.cursor(MySQLdb.cursors.DictCursor) as cursor:
cursor.execute(order_detail_query)
order_detail_result = cursor.fetchall()
order_detail_data = list(order_detail_result)
# print(order_detail_data)
cursor.execute(order_query)
order_result = cursor.fetchall()
order_data = list(order_result)
dic = {}
for d in order_detail_data:
if d['order_id'] not in dic:
dic[d['order_id']] = []
dic[d['order_id']].append(d)
order_data.append(dic)
totalData.append({"order_data":order_data, })
return Response({"totalData":totalData,},status=status.HTTP_200_OK)
else:
return Response(status=status.HTTP_400_BAD_REQUEST)
output:
{
"totalData": [
{
"order_data": [
{
"order_id": 1,
"user_id": 4,
"billing_shipping_id": 5,
"payment_method_id": 1,
"delivery_id": 2,
"txnid": "584ffb7fd622eca10a6d",
"order_no": "1-1583152683-0005",
"delivery_amount": 0.0,
"discount_amount": 0.0,
"order_total": 1.0,
"payment_status": "Paid",
"created_datetime": "2020-03-02T18:09:27",
"updated_datetime": "2020-03-02T12:39:27",
"status": "Active",
"mihpayid": "9956109007",
"payuMoneyId": "306043618"
},
{
"order_id": 2,
"user_id": 11,
"billing_shipping_id": 19,
"payment_method_id": 2,
"delivery_id": 2,
"txnid": "",
"order_no": "1-1583152785-0010",
"delivery_amount": 0.0,
"discount_amount": 0.0,
"order_total": 1.0,
"payment_status": "Unpaid",
"created_datetime": "2020-03-02T18:09:45",
"updated_datetime": "2020-03-02T12:39:45",
"status": "Active",
"mihpayid": "",
"payuMoneyId": ""
},
{
"order_id": 3,
"user_id": 12,
"billing_shipping_id": 20,
"payment_method_id": 1,
"delivery_id": 2,
"txnid": "83e066ca75437f3d05b0",
"order_no": "2-1583152964-0019",
"delivery_amount": 0.0,
"discount_amount": 0.0,
"order_total": 2.0,
"payment_status": "Paid",
"created_datetime": "2020-03-02T18:13:43",
"updated_datetime": "2020-03-02T12:43:43",
"status": "Active",
"mihpayid": "9956136979",
"payuMoneyId": "306044826"
},
{
"1": [
{
"order_detail_id": 1,
"order_id": 1,
"user_id": 4,
"product_id": 229,
"product_size_id": 982,
"size_id": 2,
"qty": 1,
"product_price": 1.0,
"order_item_status": "Placed",
"last_status_datatime": "2020-03-02T18:09:27",
"feedback": "",
"created_datetime": "2020-03-02T18:09:27",
"updated_datetime": "2020-03-02T12:39:27",
"status": "Active"
}
],
"2": [
{
"order_detail_id": 2,
"order_id": 2,
"user_id": 11,
"product_id": 229,
"product_size_id": 981,
"size_id": 1,
"qty": 1,
"product_price": 1.0,
"order_item_status": "Cancelled",
"last_status_datatime": "2020-03-02T18:10:19",
"feedback": "0",
"created_datetime": "2020-03-02T18:09:45",
"updated_datetime": "2020-03-02T12:39:45",
"status": "Active"
}
],
"3": [
{
"order_detail_id": 3,
"order_id": 3,
"user_id": 19,
"product_id": 229,
"product_size_id": 982,
"size_id": 2,
"qty": 1,
"product_price": 1.0,
"order_item_status": "Placed",
"last_status_datatime": "2020-03-02T18:32:07",
"feedback": "",
"created_datetime": "2020-03-02T18:32:07",
"updated_datetime": "2020-03-02T13:02:07",
"status": "Active"
},
]
}
]
}
]
}
what i want is:
{
"totalData": [
{
"order_data": [
{
"order_id": 1,
"user_id": 4,
"billing_shipping_id": 5,
"payment_method_id": 1,
"delivery_id": 2,
"txnid": "584ffb7fd622eca10a6d",
"order_no": "1-1583152683-0005",
"delivery_amount": 0.0,
"discount_amount": 0.0,
"order_total": 1.0,
"payment_status": "Paid",
"created_datetime": "2020-03-02T18:09:27",
"updated_datetime": "2020-03-02T12:39:27",
"status": "Active",
"mihpayid": "9956109007",
"payuMoneyId": "306043618",
"1": [
{
"order_detail_id": 1,
"order_id": 1,
"user_id": 4,
"product_id": 229,
"product_size_id": 982,
"size_id": 2,
"qty": 1,
"product_price": 1.0,
"order_item_status": "Placed",
"last_status_datatime": "2020-03-02T18:09:27",
"feedback": "",
"created_datetime": "2020-03-02T18:09:27",
"updated_datetime": "2020-03-02T12:39:27",
"status": "Active"
],}
},
{
"order_id": 2,
"user_id": 11,
"billing_shipping_id": 19,
"payment_method_id": 2,
"delivery_id": 2,
"txnid": "",
"order_no": "1-1583152785-0010",
"delivery_amount": 0.0,
"discount_amount": 0.0,
"order_total": 1.0,
"payment_status": "Unpaid",
"created_datetime": "2020-03-02T18:09:45",
"updated_datetime": "2020-03-02T12:39:45",
"status": "Active",
"mihpayid": "",
"payuMoneyId": "",
"2": [
{
"order_detail_id": 2,
"order_id": 2,
"user_id": 11,
"product_id": 229,
"product_size_id": 981,
"size_id": 1,
"qty": 1,
"product_price": 1.0,
"order_item_status": "Cancelled",
"last_status_datatime": "2020-03-02T18:10:19",
"feedback": "0",
"created_datetime": "2020-03-02T18:09:45",
"updated_datetime": "2020-03-02T12:39:45",
"status": "Active"
],
}
},
{
"order_id": 3,
"user_id": 12,
"billing_shipping_id": 20,
"payment_method_id": 1,
"delivery_id": 2,
"txnid": "83e066ca75437f3d05b0",
"order_no": "2-1583152964-0019",
"delivery_amount": 0.0,
"discount_amount": 0.0,
"order_total": 2.0,
"payment_status": "Paid",
"created_datetime": "2020-03-02T18:13:43",
"updated_datetime": "2020-03-02T12:43:43",
"status": "Active",
"mihpayid": "9956136979",
"payuMoneyId": "306044826",
"3": [
{
"order_detail_id": 3,
"order_id": 3,
"user_id": 19,
"product_id": 229,
"product_size_id": 982,
"size_id": 2,
"qty": 1,
"product_price": 1.0,
"order_item_status": "Placed",
"last_status_datatime": "2020-03-02T18:32:07",
"feedback": "",
"created_datetime": "2020-03-02T18:32:07",
"updated_datetime": "2020-03-02T13:02:07",
"status": "Active"
]
},
]
}
]
}
i am direct fetching data using raw query from databases instead of
ORM. i want to get order_detail_data inside order_data as per
order_id, per above details.
i am trying to solve this problem, but i didn't get any possible answer which could solve this problem. It would be great if anyone could help me out for what i am looking for. Advance thank you so much!.
After 16 hours struggle i found solution:
class Order_ListAPIView(APIView):
def get(self,request,format=None):
totalData=[]
if request.method == 'GET':
cur,conn = connection()
order_query = ''' SELECT * FROM orders'''
order_detail_query = ''' SELECT * FROM order_details LEFT JOIN orders ON order_details.order_detail_id = orders.order_id '''
with conn.cursor(MySQLdb.cursors.DictCursor) as cursor:
cursor.execute(order_detail_query)
order_detail_result = cursor.fetchall()
order_detail_data = list(order_detail_result)
# print(order_detail_data)
cursor.execute(order_query)
order_result = cursor.fetchall()
order_data = list(order_result)
dic = {}
def merge_order_data_and_detail(order_data, order_detail_data):
for d in order_detail_data:
if d['order_id'] not in dic:
dic[d['order_id']] = []
dic[d['order_id']].append(d)
for o in order_data:
if o['order_id'] in dic:
o['order_detail_data'] = dic[o['order_id']]
merge_order_data_and_detail(order_data, order_detail_data)
totalData.append({"order_data":order_data, })
return Response({"totalData":totalData,},status=status.HTTP_200_OK)
else:
return Response(status=status.HTTP_400_BAD_REQUEST)
How would I get the names of the keys, for example [800, 801] (the key names are unknown) with objectpath.
It is easy in jmespath: keys(#).
"groups": {
"800": {
"short_name": "22",
"oname": "11",
"group": 8,
"title": "SS",
"name": "33",
"onames": [""],
"alt_name": False,
"waytype": 1,
"multiple": 1,
"primary": 1
},
"801": {
"short_name": "ss",
"oname": "zz",
"group": 8,
"title": "ss",
"name": "bbb",
"onames": [""],
"alt_name": False,
"waytype": 1,
"multiple": 1,
"primary": 0
},
let your object is assigned to name variable
const name = { "groups": {
"800": {
"short_name": "22",
"oname": "11",
"group": 8,
"title": "SS",
"name": "33",
"onames": [""],
"alt_name": false,
"waytype": 1,
"multiple": 1,
"primary": 1
},
"801": {
"short_name": "ss",
"oname": "zz",
"group": 8,
"title": "ss",
"name": "bbb",
"onames": [""],
"alt_name": false,
"waytype": 1,
"multiple": 1,
"primary": 0
} } }
Use for loop to get the key name as
for(var num in name.groups) {
console.log(num);
}
and to get the values of key
for(var num in name.groups) {
console.log(name.groups[num]);
}
This is my JSON file and I want to sum all values of number key. How can i do that with Python?
{
"took": 0,
"timed_out": false,
"_shards": {
"total": 5,
"successful": 5,
"skipped": 0,
"failed": 0
},
"hits": {
"total": 7,
"max_score": 1.0,
"hits": [{
"_index": "test",
"_type": "json",
"_id": "5878",
"_score": 1.0,
"_source": {
"data_type": "click",
"number": 1,
"date": "1397/05/14",
"host_id": "1231"
}
}, {
"_index": "test",
"_type": "json",
"_id": "1548",
"_score": 1.0,
"_source": {
"data_type": "click",
"number": 1,
"date": "1397/05/14",
"host_id": "1231"
}
}, {
"_index": "test",
"_type": "json",
"_id": "2751",
"_score": 1.0,
"_source": {
"data_type": "click",
"number": 1,
"date": "1397/05/14",
"host_id": "1231"
}
}, {
"_index": "test",
"_type": "json",
"_id": "8363",
"_score": 1.0,
"_source": {
"data_type": "click",
"number": 1,
"date": "1397/05/14",
"host_id": "1231"
}
}, {
"_index": "test",
"_type": "json",
"_id": "551",
"_score": 1.0,
"_source": {
"data_type": "click",
"number": 1,
"date": "1397/05/14",
"host_id": "1231"
}
}, {
"_index": "test",
"_type": "json",
"_id": "2195",
"_score": 1.0,
"_source": {
"data_type": "click",
"number": 1,
"date": "1397/05/14",
"host_id": "1231"
}
}, {
"_index": "test",
"_type": "json",
"_id": "2990",
"_score": 1.0,
"_source": {
"data_type": "click",
"number": 1,
"date": "1397/05/14",
"host_id": "1231"
}
}]
}
}
import json
data = '{"took": 0, "timed_out": false, "_shards": {"total": 5, "successful": 5, "skipped": 0, "failed": 0 }, "hits": {"total": 7, "max_score": 1.0, "hits": [{"_index": "test", "_type": "json", "_id": "5878", "_score": 1.0, "_source": {"data_type": "click", "number": 1, "date": "1397/05/14", "host_id": "1231"} }, {"_index": "test", "_type": "json", "_id": "1548", "_score": 1.0, "_source": {"data_type": "click", "number": 1, "date": "1397/05/14", "host_id": "1231"} }, {"_index": "test", "_type": "json", "_id": "2751", "_score": 1.0, "_source": {"data_type": "click", "number": 1, "date": "1397/05/14", "host_id": "1231"} }, {"_index": "test", "_type": "json", "_id": "8363", "_score": 1.0, "_source": {"data_type": "click", "number": 1, "date": "1397/05/14", "host_id": "1231"} }, {"_index": "test", "_type": "json", "_id": "551", "_score": 1.0, "_source": {"data_type": "click", "number": 1, "date": "1397/05/14", "host_id": "1231"} }, {"_index": "test", "_type": "json", "_id": "2195", "_score": 1.0, "_source": {"data_type": "click", "number": 1, "date": "1397/05/14", "host_id": "1231"} }, {"_index": "test", "_type": "json", "_id": "2990", "_score": 1.0, "_source": {"data_type": "click", "number": 1, "date": "1397/05/14", "host_id": "1231"} }] } } '
myk = json.loads(data)
count = 0
target = myk['hits']['hits']
for l in target:
for k in l:
if k == "_source":
count += l[k]['number']
print(count)
output:
7
>>>
Loading data from a json file
import json
with open('data.json') as f:
data = json.load(f)
count = 0
target = data['hits']['hits']
for l in target:
for k in l:
if k == "_source":
count += l[k]['number']
print(count)
7
>>>
I have a list of dicts like this
[
{
"subject_id": 1,
"subject_name": "HR Sector 0",
"id": 1,
"name": "parent2",
"value": 10.6
},
{
"subject_id": 18,
"subject_name": "Test11",
"id": 1,
"name": "parent2",
"value": 12
},
{
"subject_id": 2,
"subject_name": "AG1",
"id": 2,
"name": "Customer Delivery Dpt. 1",
"value": 17
},
{
"subject_id": 3,
"subject_name": "Finance Group 2",
"id": 2,
"name": "Customer Delivery Dpt. 1",
"value": 1.5
},
{
"subject_id": 10,
"subject_name": "test",
"id": 2,
"name": "Customer Delivery Dpt. 1",
"value": 10
},
{
"subject_id": null,
"subject_name": null,
"id": 3,
"name": "Technology Team 2",
"value": null
},
{
"subject_id": 8,
"subject_name": "Group 4",
"id": 5,
"name": "Accounting Group 4",
"value": 10
},
{
"subject_id": null,
"subject_name": null,
"id": 9,
"name": "PG2",
"value": null
}
]
I want to convert it into nested JSON and ignore null values to get below result set
[
{
"id": 1,
"name": "parent2",
"subjects”: [
{”subject_id": 1,
"subject_name": "HR Sector 0",
"value": 10.6
},
{”subject_id": 18,
"subject_name": "Test11",
"value": 12
}
]
},
{
"id": 2,
"name": "Customer Delivery Dpt. 1",
"subjects”: [
{“subject_id": 2,
"subject_name": "AG1",
"value": 17
},
{“subject_id": 3,
"subject_name": "Finance Group 2",
"value": 1.5
},
{“subject_id": 10,
"subject_name": “test”,
"value": 10
}
]
},
{
"id": 3,
"name": "Technology Team 2",
"subjects”: []
},
{
"id": 5,
"name": "Accounting Group 4",
"subjects” : [
{ "subject_id": 8,
"subject_name": "Group 4",
"value": 10
}
]
},
{
"id": 9,
"name": "PG2",
"subjects”: []
}
]
import json
arr = [
{
"subject_id": 1,
"subject_name": "HR Sector 0",
"id": 1,
"name": "parent2",
"value": 10.6
},
{
"subject_id": 18,
"subject_name": "Test11",
"id": 1,
"name": "parent2",
"value": 12
},
{
"subject_id": 2,
"subject_name": "AG1",
"id": 2,
"name": "Customer Delivery Dpt. 1",
"value": 17
},
{
"subject_id": 3,
"subject_name": "Finance Group 2",
"id": 2,
"name": "Customer Delivery Dpt. 1",
"value": 1.5
},
{
"subject_id": 10,
"subject_name": "test",
"id": 2,
"name": "Customer Delivery Dpt. 1",
"value": 10
},
{
"subject_id": None,
"subject_name": None,
"id": 3,
"name": "Technology Team 2",
"value": None
},
{
"subject_id": 8,
"subject_name": "Group 4",
"id": 5,
"name": "Accounting Group 4",
"value": 10
},
{
"subject_id": None,
"subject_name": None,
"id": 9,
"name": "PG2",
"value": None
}
]
def process_arr_to_json(arr):
newArr = []
addedIds = {}
for item in arr:
if(addedIds.get(item["id"]) is None):
formatted_item = {"subjects":[]}
newArr.append(formatted_item)
addedIds[item["id"]] = {"idx": 0, "pos": len(newArr)-1} #index in the dictionary for the subject item
else:
formatted_item = newArr[addedIds[item["id"]]["pos"]]
addedIds[item["id"]]["idx"] += 1
for k,v in item.items():
if(v is not None):
if(k == "id" or k == "name"):
formatted_item[k] = v
else:
if(len(formatted_item["subjects"]) <= addedIds[item["id"]]["idx"]):
formatted_item["subjects"].append({k:v})
else:
formatted_item["subjects"][addedIds[item["id"]]["idx"]][k] = v
print(newArr)
return json.dumps(newArr)
if __name__ == "__main__":
process_arr_to_json(arr)
my solution
Please see code below to form the merged results
import json
def process_items(items):
results = {}
for item in items:
results[item['id']] = {
'id': item['id'],
'name': item['name'],
}
to_append = {}
for k in ['subject_id', 'value', 'subject_name']:
if item.get(k):
to_append[k] = item[k]
results[item['id']].setdefault('subjects', [])
if to_append:
results[item['id']]['subjects'].append(to_append)
return results
items = [
{
"subject_id": 1,
"subject_name": "HR Sector 0",
"id": 1,
"name": "parent2",
"value": 10.6
},
{
"subject_id": 18,
"subject_name": "Test11",
"id": 1,
"name": "parent2",
"value": 12
},
{
"subject_id": 2,
"subject_name": "AG1",
"id": 2,
"name": "Customer Delivery Dpt. 1",
"value": 17
},
{
"subject_id": 3,
"subject_name": "Finance Group 2",
"id": 2,
"name": "Customer Delivery Dpt. 1",
"value": 1.5
},
{
"subject_id": 10,
"subject_name": "test",
"id": 2,
"name": "Customer Delivery Dpt. 1",
"value": 10
},
{
"subject_id": None,
"subject_name": None,
"id": 3,
"name": "Technology Team 2",
"value": None
},
{
"subject_id": 8,
"subject_name": "Group 4",
"id": 5,
"name": "Accounting Group 4",
"value": 10
},
{
"subject_id": None,
"subject_name": None,
"id": 9,
"name": "PG2",
"value": None
}
]
result = process_items(items)
json.dumps(result.values()) # For python 3: json.dumps(list(results.values()))