-2

I'm using python 3.7 version. I have a python function that returns a json string. Even though I have key/value within double quotes, the function always returns key/value with single quotes. Can someone tell me how to fix this

def get_json():
    return {
       "id":"123",
       "name":"Frank"
    }

the output from above function is

{'id':'123', 'name':'Frank'}

What I need is

{"id":"123", "name":"Frank"}

Can someone help me with this issue

Prabodha
  • 520
  • 1
  • 6
  • 19
  • 1
    Use the `json` library: `json.dumps(your_dict)`. – Klaus D. Nov 18 '20 at 07:34
  • 1
    You're not returning a json string, that's a dictionary. Use a json encoding library if you want to turn it into a json string. – flakes Nov 18 '20 at 07:36
  • 3
    Does this answer your question? [How to create a Python dictionary with double quotes as default quote format?](https://stackoverflow.com/questions/18283725/how-to-create-a-python-dictionary-with-double-quotes-as-default-quote-format) – ashraful16 Nov 18 '20 at 07:37
  • Unless you are specifically asking about how to solve a cross-version compatibility problem (in which case your question should obviously describe that problem) you should not mix the [tag:python-2.7] and [tag:python-3.x] tags. – tripleee Nov 18 '20 at 07:45

3 Answers3

1

Your function is not returning a JSON anything, it's returning a Python dict object, and Python prints strings with single quotes by default.

If you want JSON, serialise the data to json (usually at the edge) using json.dumps.

Masklinn
  • 34,759
  • 3
  • 38
  • 57
1

In Python both {'id':'123', 'name':'Frank'} and {"id":"123", "name":"Frank"} represents same thing, in this case dictionary.

If you need string instead of dict, you can dump your data.

import json

def get_json():
    return json.dumps({
       "id":"123",
       "name":"Frank"
    })

It returns a string(not dictionary) '{"id": "123", "name": "Frank"}'

ErdoganOnal
  • 800
  • 6
  • 13
1

The __str__ class in python is responsible for string representation with both the cases to print your object. Both single quotes and double quotes describes the value returned by the object. However you are working with json, you might have problem encountering return object. The solution is simple -

import json
def get_json():
    return json.dumps({
       "id":"123",
       "name":"Frank"
    })
Raghav Gupta
  • 454
  • 3
  • 12