0

So I get this:

In [5]: json.dumps({'dic':['a', 'b', 'c']})
Out[5]: '{"dic": ["a", "b", "c"]}'

Is there a way to get output: '{"dic": '["a", "b", "c"]'}' str(list) basically?

Works when list provided alone:

In [2]: json.dumps(['a', 'b', 'c'])
Out[3]: '["a", "b", "c"]'
Murphy
  • 536
  • 6
  • 13
  • 2
    Why? The output `json.dumps` gave you is the correct JSON serialization of the input you provided. – user2357112 Oct 17 '18 at 19:59
  • Its just to support a use case that I have to convert all individual list vals in a dict to str – Murphy Oct 17 '18 at 20:03
  • 1
    Possible duplicate of [How to change json encoding behaviour for serializable python object?](https://stackoverflow.com/questions/16405969/how-to-change-json-encoding-behaviour-for-serializable-python-object) – Mike Scotty Oct 17 '18 at 20:15

3 Answers3

2

It is possible to customize json.dumps by subclassing json.JSONEncoder, but that's intended for extending which types can be serialized. To change the serialization of already supported types, such as list you have to do some serious monkeypatching. See this suggested duplicate question for such a solution: How to change json encoding behaviour for serializable python object?

In this case I suggest you instead simply convert the lists in your data to strings before serializing. This can be done with this function:

import json
def predump(data):
    if isinstance(data, dict):
        return {k: predump(v) for k, v in data.items()}
    if isinstance(data, list):
        return str(data)
    return data

print(json.dumps(predump({'dic':['a', 'b', 'c']})))

output:

{"dic": "['a', 'b', 'c']"}
Håken Lid
  • 22,318
  • 9
  • 52
  • 67
0
import json

input_ = json.dumps({'dic':['a', 'b', 'c']})
output_ = json.loads(input_)

print(output_['dic'])

output: ['a', 'b', 'c']

xyz
  • 306
  • 3
  • 11
0

Sorry but you have misinterpreted this. JSON is a string representation of data. In python json.dumps will wrap your data in a string ''

In other words, it did not "work" in the code below. The list is not "stringified", it is simply encapsuled in a string ''.

In [2]: json.dumps(['a', 'b', 'c'])
Out[3]: '["a", "b", "c"]'

A more correct way to compare the results would be to print the json.dumps (as this is how the data will be interpreted when loaded back.

Meaning you should compare (these are the printed versions of above):

{"dic": ["a", "b", "c"]}  <--> ["a", "b", "c"]

summary: You have a correctly encoded JSON.

Anton vBR
  • 18,287
  • 5
  • 40
  • 46
  • Got you. Im not blaming json.dumps, just trying to find some customization over it. Improved the question. – Murphy Oct 17 '18 at 20:14