Aidis
Aidis

Reputation: 1280

Parsing formatted JSON with Python

I want to parse JSON. Its ok if I write JSON in one line

json_input = '{ "rate_of_climbing": 18.4, "speed_factor": 520}'

But if I have JSON formated then parser does not work:

json_input = '{ 
    "rate_of_climbing": 18.4, 
    "speed_factor": 520
}'

How can I get JSON to read for formatted string?

My full code:

import json
json_input = '{ 
    "rate_of_climbing": 18.4, 
    "speed_factor": 520
}'

try:
    decoded = json.loads(json_input)

    print json.dumps(decoded, sort_keys=True, indent=4)
    print "JSON parsing example: ", decoded['rate_of_climbing']
    print "Complex JSON parsing example: ", decoded['speed_factor']

except (ValueError, KeyError, TypeError):
    print "JSON format error"

Upvotes: 2

Views: 1250

Answers (2)

xiangzhuyuan_shell
xiangzhuyuan_shell

Reputation: 11

I think you can store these json data info a file;
then read all:

json_data = ''.join([line.strip() for line in open('path to json file')])

then,

_data = json.loads(json_data) 
json.dumps(_data)

Upvotes: 1

falsetru
falsetru

Reputation: 368924

Use '''triple-quoted string literals''' (or """triple-quoted string literals""") if the string contains newlines.

json_input = '''{ 
    "rate_of_climbing": 18.4, 
    "speed_factor": 520
}'''

Upvotes: 6

Related Questions