Hướng dẫn json selector python

That is the current json array I have. I want get all json objects that type=1

before filter:

[ 
        {
            "type": 1
            "name" : "name 1",
        }, 
        {
            "type": 2
            "name" : "name 2",
        }, 
        {
            "type": 1
            "name" : "name 3"
        }, 
]

after filter:

[ 
        {
            "type": 1
            "name" : "name 1",
        }, 
        {
            "type": 1
            "name" : "name 3"
        }, 
]

please help.

asked Nov 28, 2014 at 13:36

Hướng dẫn json selector python

Majid ZandiMajid Zandi

4,1615 gold badges20 silver badges29 bronze badges

3

The following snippet of code does exactly what you want, but BEWARE that your input (as written in the question) is not a valid json string, you can check here: http://jsonlint.com.

import json

input_json = """
[
    {
        "type": "1",
        "name": "name 1"
    },
    {
        "type": "2",
        "name": "name 2"
    },
    {
        "type": "1",
        "name": "name 3"
    }
]"""

# Transform json input to python objects
input_dict = json.loads(input_json)

# Filter python objects with list comprehensions
output_dict = [x for x in input_dict if x['type'] == '1']

# Transform python object back into json
output_json = json.dumps(output_dict)

# Show json
print output_json

answered Nov 28, 2014 at 14:00

2

Simply

print [obj for obj in dict if(obj['type'] == 1)] 

Example Link.

answered Nov 28, 2014 at 13:57

Andy EccaAndy Ecca

1,86914 silver badges14 bronze badges

The filter() method filters the given sequence with the help of a function that tests each element in the sequence to be true or not. Documentation for filter

>>> obj=[
...     {
...         "type": 1,
...         "name": "name 1"
...     },
...     {
...         "type": 2,
...         "name": "name 2"
...     },
...     {
...         "type": 1,
...         "name": "name 3"
...     }
... ]
>>> filter(lambda x: x['type'] == 1, obj)

>>> list(filter(lambda x: x['type'] == 1, obj))
[{'type': 1, 'name': 'name 1'}, {'type': 1, 'name': 'name 3'}]
>>> list(filter(lambda x: x['type'] == 2, obj))
[{'type': 2, 'name': 'name 2'}]

answered Mar 25, 2021 at 18:15

How do you draw a vertical line in python?

matplotlib.pyplot.vlines vs. matplotlib.pyplot.axvlineThese methods are applicable to plots generated with seaborn and pandas.DataFrame.plot, which both use matplotlib.The difference is that vlines ...

How do you read a text file in python?

Summary: in this tutorial, you learn various ways to read text files in Python.TL;DRThe following shows how to read all texts from the readme.txt file into a string:with open(readme.txt) as f: ...

Hướng dẫn dùng go.scatter documentation python

The plotly Python package exists to create, manipulate and render graphical figures (i.e. charts, plots, maps and diagrams) represented by data structures also referred to as figures. The rendering ...

How do you get a percentage in python?

There is no percentage operator in Python to calculate the percentage, but it is irrelevant to implement on your own.To calculate a percentage in Python, use the division operator (/) to get the ...

Hướng dẫn dùng check characters python

To check if a Python string contains all the characters from a list, check if each character exists in the word:Nội dung chínhStep-by-step GuideFurther ReadingThe in OperatorThe String.index() ...

Hướng dẫn dùng sort meaning python

Xin chào mọi người. Ngôn ngữ lập trình Python 3 có sẵn 2 hàm sorted() và sort(), vậy hôm nay chúng ta hãy cùng hiểu xem các hàm này hoạt động thế nào.Hàm ...

Hướng dẫn python class type hint

New in version 3.5.Source code: Lib/typing.pyNoteThe Python runtime does not enforce function and variable type annotations. They can be used by third party tools such as type checkers, IDEs, ...

How do you crawl data from a website in python?

Web crawling is a powerful technique to collect data from the web by finding all the URLs for one or multiple domains. Python has several popular web crawling libraries and frameworks.In this ...

Hướng dẫn swap trong python

Trong bài viết này, mình xin giới thiệu 1 số thủ thuật hay mà mình biết trong Python1. swap 2 biếnvới một vài ngôn ngữ thì việc swap giá trị của 2 biến có ...

Hướng dẫn python 2d extrapolation

Hướng dẫn is prime number pythonExample to check whether an integer is a prime number or not using for loop and if...else statement. If the number is not prime, its explained in output why it is ...

Hướng dẫn gumroad python

Tracking your Gumroad sales using Python (feat. Notion API)IntroductionNotion is an incredible software that allows creators develop, publish, maintain content with little to no effort. Creator ...

How do you concatenate strings in python 3?

There are few guarantees in life: death, taxes, and programmers needing to deal with strings. Strings can come in many forms. They could be unstructured text, usernames, product descriptions, ...

How to remove space in python output

Python provides various ways to remove white-spaces from a String. This article will focus of some of the efficient techniques to remove spaces from a String.Either of the following techniques can be ...

Hướng dẫn dùng dataframe indices python

Trong bài trước ta đã tìm hiểu về pandas cũng như cách cài đặt thư viện này, vậy thì trong bài này ta sẽ tìm hiểu về Pandas Object, một kiến thức quan trọng ...

Hướng dẫn python json splitlines

Python return to previous loopTry nesting the first while loop inside of the second. Itll run your calculation code first, check to see if youd like to do another, and then return to the top of the ...

Python return to previous loop

Try nesting the first while loop inside of the second. Itll run your calculation code first, check to see if youd like to do another, and then return to the top of the while True: loop to do ...

Hướng dẫn is in python

Nhóm phát triển của chúng tôi vừa ra mắt website langlearning.net học tiếng Anh, Nga, Đức, Pháp, Việt, Trung, Hàn, Nhật, ... miễn phí cho tất cả mọi người. Là ...

How to input 2 integers in python

I wonder if it is possible to input two or more integer numbers in one line of standard input. In C/C++ its easy:C++:#include int main() { int a, b; std::cin >> a ...

How to search multiple values in array php?

I need to get the keys from values that are duplicates. I tried to use array_search and that worked fine, BUT I only got the first value as a hit.I need to get both keys from the duplicate values, in ...

Hướng dẫn parametric test python

There are different types of statistical tests used with data, each used to find out a different insight. When we have data into groups and we need to find out a few properties about them, the ...

How do i host a flask api in python?

So we have created our Flask API. Now what? How are we going to share our application to the world? We found the best way to do it without wasting time setting up servers. The only thing you need is ...

How do you write to top of file in python?

In modes a or a+, any writing is done at the end of the file, even if at the current moment when the write() function is triggered the files pointer is not at the end of the file: the pointer is ...

How to shorten a decimal in python

You want to round your answer.round(value,significantDigit) is the ordinary solution to do this, however this sometimes does not operate as one would expect from a math perspective when the digit ...

Hướng dẫn dùng setup.py python

Hướng dẫn tạo package PythonTutorial này mình sẽ hướng dẫn cách tạo package cho một project Python cơ bản. Bao gồm:Structure packageNecessary filesBuild the packageUpload to ...

How do i open a file encoding in python?

I have a Python codebase, built for Python 3, which uses Python 3 style open() with encoding parameter:https://github.com/miohtama/vvv/blob/master/vvv/textlineplugin.py#L47 with open(fname, rt, ...

Static method python là gì

Instance, class, static method trong PythonTrong bài hướng dẫn này, mình sẽ giúp làm sáng tỏ về 3 loại phương thức trong Python: Instance, Class và Static method. Nếu bạn ...

Hướng dẫn python mask list

Trong bài trước ta đã học được các thao tác tính toán trên mảng từ cơ bản đến nâng cao với NumPy. Trong việc tính toán và xử lý dữ liệu, thì lọc dữ ...

Hướng dẫn python color code

Chúng ta đã kết thúc chuỗi các bài liên quan đến công việc tùy chỉnh các tham số cơ bản của hình vẽ như: Axis, Label, Ticks, Spines, Legends. Trong bài này chúng ta ...

How do you make a simple game in python?

Learn how to make a simple game with Python!This is a post by Tutorial Team Member Julian Meyer, a 13-year-old python developer. You can find him on and Twitter.Have you ever wondered how video games ...

Hướng dẫn dùng python linux python

Hướng dẫn cài đặt, lập trình Python trên Ubuntu (Linux).(Xem thêm: Hướng dẫn cài đặt, lập trình Python trên Windows)Cài Python qua repositoryĐây là cách đơn ...

Hướng dẫn dùng pow define python

Hàm pow() trong Python trả về giá trị của xy.Nội dung chínhTrả về giá trị1. Ví dụ nhanh về hàm NumPy power () trong Python2. Cú pháp của hàm NumPy power ()2.1 Tham số ...

Hướng dẫn python black arguments

Logical operators in python with exampleOperators are used to perform operations on values and variables. These are the special symbols that carry out arithmetic and logical computations. The value ...

Logical operators in python with example

Operators are used to perform operations on values and variables. These are the special symbols that carry out arithmetic and logical computations. The value the operator operates on is known as ...

Python print all float digits

For a scientific application I need to output very precise numbers, so I have to print 15 significant figures. There are already questions on this topic here, but they all concern with truncating the ...

Hướng dẫn dùng updating pip python

Dưới đây là các thông tin và kiến thức về chủ đề cách update pip hay nhất do chính tay đội ngũ ezcach chúng tôi biên soạn và tổng hợp:Nội dung chính2. Làm ...