I wrote a Python method to convert an object and a subset of its attributes into a JSON string with a given field as the key
There's a lot of string concatenation, and I'm not too sure what the best way to do that in Python is.
Also wondering if attr.replace('"','\"')
is sufficient to sanitise input?
def to_json_with_key(nodes, key, fields, insertIndex=False):
i=0
s="{"
for node in nodes:
s += '"%s":{' % getattr(node,key)
attrs=[]
for field in fields:
attr = getattr(node,field)
if not isinstance(attr,int) and not isinstance(attr,float) and not isinstance(attr,long):
attrs.insert(0, '"%s":"%s"' % (field, attr.replace('"','\"') ))
else:
attrs.insert(0, '"%s":%s' % (field, attr ))
if (insertIndex):
s+='index:%d,' % i
i=i+1
s+=','.join(attrs) + "},"
s = s.rstrip(",") + "}"
return s
Sample input:
to_json_with_key(myObj, "title", fields=["length","time_offset"], insertIndex=True)
Sample output:
{"Introduction_to_Lists":{index:0,"length":128,"time_offset":0,
"Pass_by_Reference":{index:1,"length":84,"time_offset":128}}