4

I am new to python and trying to parse the json file and fetch the required field based on condition.

eg., if status = true, then print name

Json file:

[
  {
    "id": "12345",
    "name": "London",
    "active": true,
    "status": "true",
    "version": "1.0",
    "tags": [
    ]
  },
  {
    "id": "12457",
    "name": "Newyork",
    "active": true,
    "status": "false",
    "version": "1.1",
    "tags": [
    ]
  },
]

expected output:

name : London

Please help me on this. Thank you in advance.

2 Answers 2

5
>>> import json
>>> obj = json.loads('[ { "id": "12345", "name": "London", "active": true, "status": "true", "version": "1.0", "tags": [ ] }, { "id": "12457", "name": "Newyork", "active": true, "status": "false", "version": "1.1", "tags": [ ] } ]')
>>> print "Names:", ",".join(x["name"] for x in obj if x["status"] == "true")
Names: London

Your JSON is invalid. Remove the comma as below:

[
  {
    "id": "12345",
    "name": "London",
    "active": true,
    "status": "true",
    "version": "1.0",
    "tags": [
    ]
  },
  {
    "id": "12457",
    "name": "Newyork",
    "active": true,
    "status": "false",
    "version": "1.1",
    "tags": [
    ]
  },
   ^__________Remove this comma!
]
Sign up to request clarification or add additional context in comments.

4 Comments

Thank you for the quick response, below is the error which i have got Traceback (most recent call last): File "sample2.py", line 2, in <module> obj = json.loads("/home/dir/testing/file") File "/usr/lib64/python2.6/json/__init__.py", line 307, in loads return _default_decoder.decode(s) File "/usr/lib64/python2.6/json/decoder.py", line 319, in decode obj, end = self.raw_decode(s, idx=_w(s, 0).end()) File "/usr/lib64/python2.6/json/decoder.py", line 338, in raw_decode raise ValueError("No JSON object could be decoded") ValueError: No JSON object could be decoded
Thats because of a trailing comma in your original JSON. I fixed that in my code above.
Hi Thrustmaster, I have used the above code but the same error.. I am passing json content through file(json.loads("/home/dir/testing/file") ) Am i missing anything? please help me
Thank you thrustmaster for helping me on this. When i paste the code and execute. it is working as expected. but when i pass json content as file, it is throwing those errors. I have checked the file content, there is no comma, in the end of file. Could you please share how to pass json content through file instead having json content directly in the code.
-1

You can get all info about json parsing here.

http://docs.python.org/3.3/library/json.html

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.