I have the following model:
class Car(models.Model):
data = models.TextField(default="[]")
Also, I have the following serializer:
class CarSerializer(serializers.ModelSerializer):
data = serializers.ListField(child=serializers.CharField())
The REST API gets data and saves it as text field. In my to_dict method of Car, I want to convert self.data into JSON and return the dict:
def to_dict(self):
result = dict()
result['data']= json.loads(self.data)
return result
But it fails with the error:
json.decoder.JSONDecodeError: Expecting value: line 1 column 2 (char 1)
As I understand, the reason is that self.data is:
"['a', 'b', 'c']"
And not:
'["a", "b", "c"]'
I'm familiar with JsonField, but since I'm using SQLite without JSON1 externation, I can't use it. How can I convert self.data to JSON?
You can use python json.dumps() method to convert string into json format and then use json.loads() to convert json into python object.
import json
def to_dict(self):
result = dict()
data = json.dumps(self.data)
result['data'] = json.loads(data)
return result
The simplest way to solve this problem is json.loads(self.data.replace('\'','\"')).
Replace ' to ".
Or you can try eval(self.data)
you can watch a sample here about the usage of eval
Related
class_object = ModelClass(title=entity_object['title'],
entities_definition_key=entity_object['entities_definition_key'],
orderId=entity_object['orderId'],uid = json.dumps( uuid.uuid4(),
cls=UUIDEncoder))
ModelClass is mongoengine model class
json_output = class_object.serializing_method()
final_list.append(json_output)
another_class_object = AnotherModelClass(workflowId=body['workflowId'],entities_list=final_list)
another_class_object.save()
save() to mongodb
final_dict={}
final_dict['entities_list'] = another_class_object.entities_list
return HttpResponse(json.dumps({'entity_definition_dict':entity_definition_dict}))
output-{'uid': "\"74b1900ccfbd44234563805ac0279d\""}
I don't know why you need to call json.dumps() on the UUID. It causes all your problems and I can't imagine a problem it would fix.
class_object = ModelClass(
...,
uid = uuid.uuid4().hex,
)
I'm getting data from an API and saving into a list called data[].
After this, I'm sending these data to another class to format it.
I want to create a dict, so I can save these data. I'm trying to do something like this:
import json
import datetime
class MovieFormatter():
def format(self, data):
data = {
"movie_info_name": data['title']
"movie_info_duration": data['duration']
"movie_info_description": data['synopsis']
"movie_info_genres": data['genres']
"movie_info_actor": data['cast']
"movie_info_director": data['director']
data['trailers'] = data.get('trailers') or []
"dictionary": [{'url': x['url'], 'type': x['type']} for x in data['images'] + data['trailers']]
}
return data
Is this the right way to do?
It seems that the data object passed to your function is already a dictionary, from the way it has been indexed e.g. data['title'].
Try this :
_in_data = ["a","b","c"]
_out_data = ["x","y","z"]
_dict={}
print(_dict)
for i in range (len(_in_data)):
_dict[_in_data[i]]=_out_data[i]
print(_dict)
I am trying to find a way to parse a JSON string and save them into mysql.
This is my json!
{"title": My title, "desc": mydesc, "url": http//example.com}
From now i don't have problem to save all json into one column usining json.dumps() so actually I'm trying to parse each joson data string to send him to mysql table. Title | Desc | Url.
This is my python code for desc example (pyspider-resultdb.py)
def _parse(self, data):
for key, value in list(six.iteritems(data)):
if isinstance(value, (bytearray, six.binary_type)):
data[key] = utils.text(value)
if 'result' in data:
decoded = json.loads(data['result'])
data['result'] = json.dumps(decoded['desc'])
return data
def _stringify(self, data):
if 'result' in data:
decoded = json.loads(data['result'])
data['result'] = json.dumps(decoded['desc'])
return data
It's unclear from your question what you trying to achieve, but If your question is how to convert JSON to python dict and then load to the table, then that's how you can do it:
my_dict = json.loads('{"title": "foo", "dest": "bar"}')
curs.execute('INSERT INTO test (title, dest) values(%(title)s, %(dest)s)', my_dict)
For a custom object I am able to encode into json using JSONEncoder.
class CustomEncoder(JSONEncoder):
def encode(self, custom):
prop_dict = {}
for prop in Custom.all_properties_names():
if custom.__getattribute__(prop) is not None:
if prop is 'created_timestamp':
prop_dict.update({prop: custom.__getattribute__(
prop).isoformat()})
else:
prop_dict.update({prop: custom.__getattribute__(prop)})
return prop_dict
To generate json, I am using json.dumps(custom, cls=CustomEncoder, indent=True)
Now I have a list of Custom class objects. How do convert the list to json?
custom_list = //get custom object list from service
How do I convert the whole list to json? Do I need to iterate and capture json of each custom object and append to a list with comma separated? I feel like there should be something straightforward I am missing here.
The custom encoder is called only when needed. If you have a custom thing that the JSON library thinks it can encode, like a string or dictionary, the custom encoder won't be called. The following example shows that encoding an object, or a list including an object, works with a single custom encoder:
import json
class Custom(object):
pass
class CustomEncoder(json.JSONEncoder):
def default(self, o):
if isinstance(o, Custom):
return 'TASTY'
return CustomEncoder(self, o)
print json.dumps( Custom(), cls=CustomEncoder )
print json.dumps( [1, [2,'three'], Custom()], cls=CustomEncoder )
Output:
"TASTY"
[1, [2, "three"], "TASTY"]
In my way, I convert object to dict then using json.dumps list of dict:
def custom_to_dict(custom):
return {
'att1': custom.att1,
'att2': custom.att2,
...
}
#custom_list is your list of customs
out = json.dumps([custom_to_dict(custom) for custom in custom_list])
It might be helpful
I'm using Colander to convert JSON strings to Python Objects and vice versa in a Pyramid/Cornice based project.
Is there any way that you can serialize/deserialize to different names/keys ?
Here is the Colander Schema:
class CommentSchema(MappingSchema):
resource_id = SchemaNode(Int(), name="resourceID", location="body")
text = SchemaNode(String(), name="text", location="body")
And here is the input JSON
{"text":"Hello!", "resourceID":12}
It is being converted to :
{u'text': u'Hello!', u'resourceID': 12}
Here is my question, can I have the same input JSON converted to the following?
{u'full_text': u'Hello!', u'resource_id': 12}
Thanks for your help.
I eventually had to do it manually.
Whatever is received from the JSON is used to construct a Data Object. The Object would have a custom function to map the data to the desired output format, and you pass the output to the serializer:
data_schema = DataSchema().deserialize(self.request.json)
data_obj = DataObject(data_schema**) // or DataObject(full_text = data_schema['text'], resource_id = data_schema['resourceID'])
#
# ...
#
rbody = DataSchema().serialize(data_obj.map_dump())
return Response(body=rbody, status_code=201)
And the DataObject would look like this:
class DataObject(Object):
def __init__(self, text, resourceID): // or __init__(self, full_text, resource_id)
self.text = text
self.resourceID = resourceID
def map_dump(self):
output['full_text'] = self.text
output['resource_id'] = self.resource
return output