0

my json file is in dictionary format, I want to read it into my Python. This is my original file.

fruit.json:

{
    "Q":"Is it red?",
    "yes":{
        "answer":"apple"
    },
    "no":{
        "Q":"Is it yellow",
        "yes":{
            "answer":"banana"
        },
        "no":{
            "Q":"Is it sweet?",
            "yes":{
                "answer":"mango"
            },
            "no":{
                "Q":"Bigger than strawberry?",
                "yes":{
                    "answer":"lemon"
                },
                "no":{
                    "answer":"blueberry"
                }
            }
        }
    }
}

After reading them, I want to know if it's possible to print them in the same format too.

Code:

 import json
    import sys


    s = json.loads(open(r'C:\Users\makiyo\fruit.json').read())
    print(s)
    print(type(s))
    print("--------")
    print(json.dumps(s, indent=4), file=sys.stderr)

Type of s is dict:

{'Q': 'Is it red?', 'no': {'Q': 'Is it yellow', 'no': {'Q': 'Is it sweet?', 'no': {'Q': 'Bigger than strawberry?', 'no': {'answer': 'blueberry'}, 'yes': {'answer': 'lemon'}}, 'yes': {'answer': 'mango'}}, 'yes': {'answer': 'banana'}}, 'yes': {'answer': 'apple'}}

Output:

{
    "Q": "Is it red?",
    "no": {
        "Q": "Is it yellow",
        "no": {
            "Q": "Is it sweet?",
            "no": {
                "Q": "Bigger than strawberry?",
                "no": {
                    "answer": "blueberry"
                },
                "yes": {
                    "answer": "lemon"
                }
            },
            "yes": {
                "answer": "mango"
            }
        },
        "yes": {
            "answer": "banana"
        }
    },
    "yes": {
        "answer": "apple"
    }
}

This is not the format from the fruit.json, I don't know why they change the 'yes'/'no' location like this.

Makiyo
  • 441
  • 5
  • 23

2 Answers2

1

One option if you aren't changing anything would be to keep a reference to the string you parse into JSON.

with open(r'C:\Users\makiyo\fruit.json') as input_file:
    raw = input_file.read()
    s = json.loads(raw)
    assert type(raw) is str
    assert type(s) is dict

If you don't want to hold onto the reference, or if you want to edit the dict, you can use json.dumps.

output = json.dumps(s)
assert type(output) is str
Brett Beatty
  • 5,690
  • 1
  • 23
  • 37
  • Your code is neat! But I still need to learn why it works with this :) I have a question, I have another json file which is in Mandarin, the encoding works quite well no worries! But when it prints the raw, some of the yes and no have two tabs on the front. The format is almost the same, just some of the lines might be locate one more tab behind. Or is it just the problem of my json file? Thank you! :) – Makiyo Oct 25 '17 at 03:56
  • I haven't done anything with different encodings, so I can't be much help. – Brett Beatty Oct 25 '17 at 17:38
0

A dictonary in python can not preserve the order of items in which they were added. json.dumps() creates a dict out of the provided json.

You can use a OrderedDict to preserve the order.

from collections import OrderedDict
s = json.loads(open(r'C:\Users\makiyo\fruit.json').read(), object_pairs_hook=OrderedDict)

# recursively print in desired format.
def print_json(json):
    for k, v in json.iteritems():
        print k, v
        if type(v) is OrderedDict:
            print_json(v)
print_json(s)

Or you can use python 3.6 - Dictionaries are ordered in Python 3.6+

Hemant_Negi
  • 1,910
  • 1
  • 20
  • 25