2

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"
2
  • The way you define the Python string doesn't work. The json module works just fine... Commented Dec 24, 2013 at 12:29
  • Presumably you are getting a SyntaxError here; if you are getting a different error, can you remove the try and except lines (unindent the rest) and show us the error you are getting? Include the sample input that reproduces the problem. Commented Dec 24, 2013 at 12:32

2 Answers 2

6

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
}'''
Sign up to request clarification or add additional context in comments.

Comments

1

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)

1 Comment

Thanks, maybe I will use your suggestion later!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.