1

My json file looks like this:

{"07/01/2015-08/01/2015": 
    {"ABC": [
              ["12015618727", "2015-07-29 02:32:01"], 
              ["12024079732", "2015-07-24 13:04:01"], 
              ["12024700142", "2015-07-02 00:00:00"]
             ]
    }
}

I want to extract the numbers 12015618727, 12024079732, 12024700142 from here in python.

I wrote this code:

import json
numbers=set()
input_file=open('filename', 'r')
json_decode=json.load(input_file)
for item in json_decode["07/01/2015-08/01/2015"]["ABC"]:
    for j in item:
        numbers.add(j[0])
print " ".join(str(x) for x in numbers)

But this doesn't print the numbers.

4
  • Possible duplicate of Parsing values from a JSON file in Python Commented Nov 4, 2015 at 20:12
  • SO isn't a code writing service. Please read up on the relevant subjects, make an attempt, and provide a MVE when you run into trouble. Commented Nov 4, 2015 at 20:16
  • SO on the other hand, is a question-and-answer web site. I observe that this post has no question. S.Pandit, do you have a specific question to ask? Commented Nov 4, 2015 at 20:23
  • You can access what you want by looping and using the correct dictionary keys. What have you tried? Commented Nov 4, 2015 at 20:28

1 Answer 1

1

Python has a json parsing library, see https://docs.python.org/2/library/json.html for details.

Usage:

import json
text = open("file.txt", "r").read()
obj = json.loads(text)

where obj is a python native dict object with nested arrays and dicts.

Edit:

This is the code you want.

import json
numbers=set()
input_file=open('filename.json', 'r')
json_decode=json.load(input_file)
for item in json_decode["07/01/2015-08/01/2015"]["ABC"]:
    numbers.add(item[0])
print " ".join(str(x) for x in numbers)

You iterated through each item (the two strings) and added the first letter of each string, hence 1 and 2. Next time, please provide the output you got.

Also, you should attempt to debug your code first. I added a print at the beginning of each loop, and that made the problem pretty clear.

Sign up to request clarification or add additional context in comments.

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.