Murphy
Murphy

Reputation: 556

how would I customize python json.dumps to convert a dict list value to str

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"]'

Upvotes: 0

Views: 537

Answers (3)

Håken Lid
Håken Lid

Reputation: 23074

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']"}

Upvotes: 2

Anton vBR
Anton vBR

Reputation: 18914

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.

Upvotes: 0

xyz
xyz

Reputation: 306

import json

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

print(output_['dic'])

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

Upvotes: 0

Related Questions