Can a type convert a string to a dict or list? #1506
-
I'm using VisiData as a Is there currently a way to do this? I've tried defining a type: from visidata import vd, Sheet, ColumnsSheet, AttrDict
from copy import copy
from json import loads, dumps
def jsonjson(*args):
if not args:
return None
elif not isinstance(args[0], str):
return copy(args[0])
else:
return loads(args[0], object_hook=AttrDict)
jsonjson.__name__ = 'jsonjson'
vd.addType(jsonjson, '{}', formatter=lambda fmtstr,val: dumps(val))
Sheet.addCommand('', 'type-json', 'cursorCol.type=jsonjson', 'set type of current column to JSON')
ColumnsSheet.addCommand('', 'type-json-selected', 'onlySelectedRows.type=jsonjson', 'set type of selected columns to JSON') This works in that JSON objects are recognized as dicts with the correct keys. However, after expanding the column the expanded fields are empty.
Can a type generate a dict or list this way? |
Beta Was this translation helpful? Give feedback.
Replies: 2 comments 2 replies
-
Well, I tracked this down, and it's due to You could freeze the column ( |
Beta Was this translation helpful? Give feedback.
-
If there is a command to convert/parse a column of JSON string to JSON data object for further expansion with '(' command, that'll be very handy. |
Beta Was this translation helpful? Give feedback.
Well, I tracked this down, and it's due to
ExpandedColumn
using the original columns'getValue
instead ofgetTypedValue
. This is because of thevlen
type (z#
), which can be applied to lists and dicts and strings, and converts the base value to an integer for sorting and a nicer display; this is used in the Frequency Sheet for thecount
, which is actually a list of the rows in the bin. Also you can meaningfully apply thestr
type (~
) to get the Python string representation.You could freeze the column (
'
) after applying yourjsonjson
type, and then untype the frozen column (z~
) but I think it's probably better to do=jsonjson(curcol)
or make a command that does the same (and then probably …