0

Let's assume that I have GET request with URL domain/search/?value=123 and data in JSON:

[

      {
        "id": 1,
        "value": 123,
        "value2": 123123
      },
      {
        "id": 2,
        "value": 1,
        "value2": 214
      }

]

I would like to get data where value = 123. In this case:

    [

          {
            "id": 1,
            "value": 123,
            "value2": 123123
          }
    ]

I have found information how to capture parameters from URL in this post. I wonder what I should do now to find best solution in Django. Thanks in advance.

How can I use it in views.py:

if request.method == 'GET':
        myObject = myObjectClass.objects.all()
        serializer = myObjectSerializer(myObject, many=True)
        return Response(serializer.data)

when data from JSON is not only an integer.

Community
  • 1
  • 1

3 Answers3

1

This is how to get it in python:

data = [

  {
    "id": 1,
    "value": 123,
    "value2": 123123
  },
  {
    "id": 2,
    "value": 1,
    "value2": 214
  }

]
result = None
for item in data:
    if item['value'] == 123:
       result = [item]
       break

print(result)
ruddra
  • 50,746
  • 7
  • 78
  • 101
0

Here is a javascript code to do this :-

function test()
{
//alert("Hi");
var text = '[{"id":1,"value":123,"value2":123123},{"id":2,"value":1,"value2":214}]'

json = JSON.parse(text);

var result = [];

for(var i = 0; i < json.length; i++) {
    var obj = json[i];
    if(obj['value'] == 123){
        result.push(obj);
    }

}

console.log(result);

}
Max08
  • 955
  • 1
  • 7
  • 16
0

In views.py , you can get the value of the URL through request object

    data = [

  {
    "id": 1,
    "value": 123,
    "value2": 123123
  },
  {
    "id": 2,
    "value": 1,
    "value2": 214
  }

]
print [ item for item in data if item['value'] == request.GET.get('value') ]