1

Usually my webservice built with Bottle return JSON files, which works fine. But, I've an exception that need to call a local function.

Here is what I tried to do:

import json
def getData():
    return json.dumps({'data': someData })

def function():
    try:
        # Fail
    except:
        print getData()
        print type(getData())
        json.load(getData())

So it prints:

{"data": "myData"}
<type 'str'>
[...]
AttributeError: 'str' object has no attribute 'read'

So json.dumps gives me a string. How can I use it as JSON ?

5
  • First, where is your return in front of json? Commented Feb 28, 2013 at 19:45
  • Sorry, I rewrite it to make it simple. I've forgot the return. Commented Feb 28, 2013 at 19:46
  • 2
    someData is already a dict() you just access someData ... at least it should be. If it's a string then you need to call json.load() on it Commented Feb 28, 2013 at 19:47
  • And assign it to a variable :) Commented Feb 28, 2013 at 19:48
  • @Cfreak It seems to be a dict because of the { ... }, but it's actually a string. Commented Feb 28, 2013 at 19:53

2 Answers 2

5

json.load loads JSON from a file object.

json.loads loads from a string. This is what you want.

Sign up to request clarification or add additional context in comments.

2 Comments

I knew there was a simple answer. Thank you.
Technically it's a file-like object (has read() method), so this will work: json.load(StringIO('["streaming API"]'))
2

Use json.loads instead of json.load. As per the docs.

Comments

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.