change json structure in Django - django

I've never had to change json structure before using Django models, so I may have made a completely stupid question.
I have some data in my database and want to parse it in a json format.
My view.py (a bit simplified) is:
def get_json(request):
pos = Pos.objects.filter(id=1).values('lat', 'lon','id')
return JsonResponse ({'position': list(pos)})
As a result I get this json object:
{ "position": [{"lat": "21", "id": 1, "lon": "21"}, {"lat": "22", "id": 1, "lon": "22"}, {"lat": "23", "id": 1, "lon": "23"}]}
In order to reduce the volume of unusefull data, I need to get a json structure like this:
{"id":"1", "position":{"lats":[21,22,23], "longs":[21,22,22]} }
I would be gratefull if sombody could help me

You'll need to process the data; you can do whatever you like within the view function.
pos = Pos.objects.filter(id=1).values('lat', 'lon','id')
data = {"lats": [], "longs": []}
for p in pos:
data["lats"].append(p['lat'])
data["longs"].append(p['long'])
return JsonResponse({'position': data})

Related

Using Postman How to write a test to check for duplicate ids

I would like to write a test in Postman that validates there are no duplicate values in the array of objects. Here is an example response:
This is my json response :
{
"content": [
{
"id": "88848990-c4c8-4e7d-b708-3e69e684085b",
"name": "UPDATED",
},
{
"id": "42c37e1d-eed3-4f5c-b76a-7b915c05b0bf",
"name": "Swoop ",
},
{
"id": "88848990-c4c8-4e7d-b708-3e69e684085b",
"name": "United Test Airlines",
},
I can see 2 ids that are the same I want to write a test in postman to identify any duplicates in my results. If the test picks up duplicates then it must fail, if it does not pick up any duplicates it should pass. Note I am new to postman api testing.
The short and esay solution might be:
Save all id in an array
Create a set from this array
Compare size of the array and the set. If it equals, then no duplication. If not, there is a duplication.
const res = pm.response.json();
const ids = _.map(res.content, "id");
pm.test("check duplicate id", () => {
const setIds = new Set(ids);
pm.expect(ids.length).eql(setIds.size);
})

Secondary Index not working for Database using #key

I should get the DynamoDb id for Justin. The call doesn't seem to fail. If i console.log(returned) i get an [object Object]. When i try to get to the returned.data.getIdFromUserName.id or returned.data.getIdFromUserName.email (anything else in the table) i get undefined. What am i missing?
Returned data:
{
"data": {
"getIdFromUserName": {
"items": [
{
"id": "3a5a2ks4-f137-41e2-a604-594e0c52a298",
"userName": "Justin",
"firstname": "null",
"weblink": "#JustinTimberlake",
"email": "iuiubiwewe#hotmail.com",
"mobileNum": "+0123456789",
"profilePicURI": "null",
"listOfVideosSeen": null,
"userDescription": "I wanna rock your body, please stay",
"isBlocked": false,
"GridPairs": null
}
],
"nextToken": null
}
}
}
I'd suggest getting a better idea of what console.log(returned) is printing.
Try console.log(JSON.stringify(returned, null, 2)) to inspect what is being returned.
EDIT: The data you're working with looks like this:
{
"data": {
"getIdFromUserName": {
"items": [
{
"id": "3a5a2ks4-f137-41e2-a604-594e0c52a298",
"userName": "Justin",
"firstname": "null",
"weblink": "#JustinTimberlake",
"email": "iuiubiwewe#hotmail.com",
"mobileNum": "+0123456789",
"profilePicURI": "null",
"listOfVideosSeen": null,
"userDescription": "I wanna rock your body, please stay",
"isBlocked": false,
"GridPairs": null
}
],
"nextToken": null
}
}
}
Pay close attention to the structure of that response. Both data and getIdFromUserName are maps. The content of data.getIdFromUserName is an array named items. Therefore, data.getIdFromUserName.items is an array containing the results of your query. You'll need to iterate over that array to get the data you are looking for.
For example, data.getIdFromUserName.items[0].id would be 3a5a2ks4-f137-41e2-a604-594e0c52a298
To access the email it would be data.getIdFromUserName.items[0].email.

How to iterate over a json object in Python?

I have a json object contaning currencies as listed below which I need to convert it into my model and save it into the DB. Also is there a way to save the list of models in one go?
{
"results": {
"ALL": {
"currencyName": "Albanian Lek",
"currencySymbol": "Lek",
"id": "ALL"
},
"KWD": {
"currencyName": "Kuwaiti Dinar",
"id": "KWD"
},
"LSL": {
"currencyName": "Lesotho Loti",
"id": "LSL"
},
"MYR": {
"currencyName": "Malaysian Ringgit",
"currencySymbol": "RM",
"id": "MYR"
},
"MUR": {
"currencyName": "Mauritian Rupee",
"currencySymbol": "₨",
"id": "MUR"
}
}
}
I tried this :
for key,value in currencies.results :
#print(currency)
#print(value)
However, I get the following error :
"Too many attribures to unpack, expected 2
Can someone help me with this?
I think it should be like this:
results = currencies.get('results')
for key, value in results.items(): # for python3
print(key, value)
for key, value in results.iteritems(): # python2.7
print(key, value)
You should iterate as
for result in results:
for currency in result:
print(result)

How to get JSONobject from JSONArray in postman

I am trying to automize a registration scenario in postman using test scripts
I have the following JsonArray as a response:
[
{
"id": 1,
"name": "user_A",
"cntkp": "martin",
"company": "kreativ",
"tel": "12345678",
"email": "user_A#gmail.com"
"street": "str. 0001",
"city": "DEF",
}
......
......
......
{
"id": 4,
"name": "user_B",
"cntkp": "martin",
"company": "kreativ",
"tel": "12345678",
"email": "user_B#gmail.com"
"street": "str. 0002",
"city": "NJ",
}
......
......
......
{
"id": 10,
"name": "User_C",
"cntkp": "martin",
"company": "kreativ",
"tel": "12345678",
"email": "user_C#gmail.com"
"street": "str. 0003",
"city": "ABC",
}
......
]
the array length can be dynamic and changed (in this sample is 10) and want to find the object with special email (somewhere in the array) and then get the ID from that object and make the assertion based on JsonData from this object (catch elements e.g. check name).
how can I do that?
thanks for the support.
I send a GETrequest to get all Data from Registration DB.
as response I get a JsonArray
from Json Array I need the specific Object for the assertion (e.g. object with email user_B in sample) .
I know my Email address and base on it I have to findout the ID from Object .
I can do it when I know which ID is my ID but in case it is dynamic I don't know how to search an array for it in postman to get ID
For example, to assert the company name
pm.expect(jsonData[0].company).to.equal(pm.environment.get("regDB_new_company"))
but if I dont know the ID ( only know my email) I have first to find out the ID of Object then I can asser it.
e.g.
in this case first, find the object with email "user_B#gmail.com"
then from that object get ID element (in this case 4)
then I want to assert for all data from the object
Thanks Danny, I found the solution
var arr = pm.response.json()
for(i = 0; i < arr.length; i++) {
if (arr[i].email == "userB#gmail.com") {
pm.environment.set("personID", arr[i].id)
}
}

django model serialization

I want to serialize models so:
class Schedule(models.Model):
Title = models.CharField(max_length=512)
class ScheduleEvent1(models.Model):
ScheduleContent = models.ForeignKey(Schedule)
Description = models.TextField()
class ScheduleEvent2(models.Model):
ScheduleContent = models.ForeignKey(Schedule)
AnotherField = models.TextField()
ShortDescription = models.TextField()
make smth like serializers.serialize('json', Schedule.objects.all())
The result likes
[
{
"pk": 2,
"model": "Schedule",
"fields": {
"Title": "Some Title",
"ScheduleEvent1": [
{
"pk": 19,
"model": "ScheduleEvent1",
"fields": {
"Description": "Some Descr",
}
},
{
"pk": 20,
"model": "ScheduleEvent1",
"fields": {
"Description": "Some Descr2222",
}
}
],
"ScheduleEvent2": [
{
"pk": 15,
"model": "ScheduleEvent2",
"fields": {
"AnotherField": "Some text",
"ShortDescription" : "Some text ...",
}
}
]
}
}
]
In general. I have entity tree. And I need serialize this tree from root.
tnx for help.
http://docs.djangoproject.com/en/1.3/topics/serialization/#dependencies-during-serialization
Covers the essence of this. The resulting file is not precisely what's required, since the objects won't be nested. However it is what Django produces by default and it's what Django will use for deserialization.
If you use Piston you can easily define a Handler which will produce nested JSON, but it won't be precisely as shown because Piston's JSON emitter isn't precisely in the Django format.
Getting to precisely what's hoped-for leads to extending the Django serializer to produce a nested JSON object as the natural key. See http://code.djangoproject.com/browser/django/trunk/django/core/serializers/python.py. Lines 47-59
Or, you can define a natural_key method which uses Django's 'django.core.serializers.json .Serializer` to emit the JSON serialization of the object instead of some other natural key value. This is a little weird semantically, but it may do what you want.