jakkolwiek
jakkolwiek

Reputation: 145

JSON.load won't work with json one-liner

I have the same json data in two forms - one is a one-liner, the second one is just formatted output. JSON A:

{"id":1, "name":"BoxH", "readOnly":true, "children":[{ "id":100, "name":"Box1", "readOnly":true, "children":[ { "id":1003, "name":"Box2", "children":[ { "id":1019, "name":"BoxDet", "Ids":[ "ABC", "ABC2", "DEF2", "DEFHD", "LKK" ]}]}]}]}

and JSON B:

{
   "id":1,
   "name":"BoxH",
   "readOnly":true,
   "children":[
      {
         "id":100,
         "name":"Box1",
         "readOnly":true,
         "children":[
            {
               "id":1003,
               "name":"Box2",
               "children":[
                  {
                     "id":1019,
                     "name":"BoxDet",
                     "Ids":[
                        "ABC",
                        "ABC2",
                        "DEF2",
                        "DEFHD",
                        "LKK"
                        ]
                    }
                ]
            }
        ]
    }
    ]
}

Why is it, that the code:

import json

if open('input_file.json'):
    output_json = json.load('input_file.json')

in case A throws

ValueError: No JSON object could be decoded

and the case B works correctly. I'm just wondering why is it so? I thought that the JSON A and JSON B are the same for json.load. What should I do to get the both cases working?

Upvotes: 1

Views: 790

Answers (2)

jakkolwiek
jakkolwiek

Reputation: 145

Acutally in my case there was problem with coding. As soon as I've converted the one-liner-file to UTF-8 without BOM, it started to working without any problems. The coding before was ANSI. So.. lesson learned: check the file coding.

Upvotes: 0

falsetru
falsetru

Reputation: 369424

json.load accept a file object (not file path). And you should keep the file reference. Try following:

import json

with open('input_file.json') as f:
    output_json = json.load(f)

Alternatively you can use json.loads which accept serialized json string:

import json

with open('input_file.json') as f:
    output_json = json.loads(f.read())

Upvotes: 6

Related Questions