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.

S.Pandit
  • 37
  • 1
  • 8
  • Possible duplicate of [Parsing values from a JSON file in Python](http://stackoverflow.com/questions/2835559/parsing-values-from-a-json-file-in-python) – R Nar Nov 04 '15 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. – Chad S. Nov 04 '15 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? – Robᵩ Nov 04 '15 at 20:23
  • You can access what you want by looping and using the correct dictionary keys. What have you tried? – mugabits Nov 04 '15 at 20:28

1 Answers1

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.

personjerry
  • 1,045
  • 8
  • 28