-1
votes

I'm new to JSON and Python, any help on this would be greatly appreciated.

I read about json.loads but am confused

How do I read a file into Python using json.loads?

Below is my JSON file format:

{
        "header": {
        "platform":"atm"
        "version":"2.0"
       }
        "details":[
       {
        "abc":"3"
        "def":"4"
       },
       {
        "abc":"5"
        "def":"6"
       },
       {
        "abc":"7"
        "def":"8"
       }    
      ]
    }

My requirement is to read the values of all "abc" "def" in details and add this is to a new list like this [(1,2),(3,4),(5,6),(7,8)]. The new list will be used to create a spark data frame.

2
It seems you forgot to include a question in your question. - Biffen
what is your question and what did you try? - wander95
How can I achieve the above in python. I read about json.loads but am confused :( - pavan kumar

2 Answers

3
votes

Open the file, and get a filehandle:

fh = open('thefile.json')

https://docs.python.org/2/library/functions.html#open

Then, pass the file handle into json.load(): (don't use loads - that's for strings)

import json
data = json.load(fh)

https://docs.python.org/2/library/json.html#json.load

From there, you can easily deal with a python dictionary that represents your json-encoded data.

new_list = [(detail['abc'], detail['def']) for detail in data['details']]

Note that your JSON format is also wrong. You will need comma delimiters in many places, but that's not the question.

2
votes

I'm trying to understand your question as best as I can, but it looks like it was formatted poorly.

First off your json blob is not valid json, it is missing quite a few commas. This is probably what you are looking for:

{
    "header": {
        "platform": "atm",
        "version": "2.0"
    },
    "details": [
        {
            "abc": "3",
            "def": "4"
        },
        {
            "abc": "5",
            "def": "6"
        },
        {
            "abc": "7",
            "def": "8"
        }
    ]
}

Now assuming you are trying to parse this in python you will have to do the following.

import json

json_blob = '{"header": {"platform": "atm","version": "2.0"},"details": [{"abc": "3","def": "4"},{"abc": "5","def": "6"},{"abc": "7","def": "8"}]}'
json_obj = json.loads(json_blob)

final_list = []

for single in json_obj['details']:
    final_list.append((int(single['abc']), int(single['def'])))

print(final_list)

This will print the following: [(3, 4), (5, 6), (7, 8)]