question-mark
Stuck on an issue?

Lightrun Answers was designed to reduce the constant googling that comes with debugging 3rd party libraries. It collects links to all the places you might be looking at while hunting down a tough bug.

And, if you’re still stuck at the end, we’re happy to hop on a call to see how we can help out.

I’m working on a simple API that queries elasticsearch with the Python DSL and returns JSON. I’m noticing that when I try to turn data from a search into JSON I get an issue:

s = Search(using=es_client)
s = s.filter(. . .) # some filter
s = s.query('multi_match', query='some text', fields=['field1', 'field2'])
result = s.execute()['hits']['hits']
json.dumps(result)

Object of type ‘AttrList’ is not JSON serializable

Any suggestions for how to effectively coerce the results to JSON? I expected this to be a bit easier. When I try to coerce the AttrList to JSON then I get the same error with AttrDict: Object of type 'AttrDict' is not JSON serializable

Is the only resolution here to manually iterate over all the values and coerce them to a normal list or dict?

I noticed https://github.com/elastic/elasticsearch-dsl-py/issues/748 mentions this error but I wasn’t clear if it applied to this or not.

Issue Analytics

  • State:closed
  • Created 5 years ago
  • Comments:7 (2 by maintainers)

github_iconTop GitHub Comments

2reactions
fernando-mccommented, Jun 2, 2018

@okke-formsma Fair enough. I ended up coercing the data with list() and to_dict() but given that searching for the data using the python DSL and then returning JSON is a pretty common use case I guess I thought there would be an easier solution.

I didn’t want to write the ‘raw’ queries because constructing them was more difficult.

Maybe I’m just using the tool wrong and I have a weird use case but it might be worth looking at implementing a helper function to coerce the data to JSON-serializable attributes.

1reaction
zhanwenchencommented, Jan 31, 2020

My solution: I wrote (modified) the swagger-codegen BaseModel to treat an AttrList the same way it does a list:

def to_dict(self):
        """Returns the model properties as a dict

        :rtype: dict
        """
        result = {}

        for attr, _ in self.swagger_types.items():
            value = getattr(self, attr)
            if isinstance(value, (list, AttrList)):
                result[attr] = list(map(
                    lambda x: x.to_dict() if hasattr(x, "to_dict") else x,
                    value
                ))
            elif hasattr(value, "to_dict"):
                result[attr] = value.to_dict()
            elif isinstance(value, dict):
                result[attr] = dict(map(
                    lambda item: (item[0], item[1].to_dict())
                    if hasattr(item[1], "to_dict") else item,
                    value.items()
                ))
            else:
                result[attr] = value
        return result
Read more comments on GitHub >

github_iconTop Results From Across the Web

Attribute Definition & Meaning - Merriam-Webster
noun ; 1 · a quality, character, or characteristic ascribed to someone or something. has leadership attributes ; 2 · an object closely...
Read more >
Attribute Definition & Meaning - Dictionary.com
something attributed as belonging to a person, thing, group, etc.; a quality, character, characteristic, or property: Sensitivity is one of his attributes.
Read more >
ATTRIBUTE | definition in the Cambridge English Dictionary
a quality or feature of a person or thing, esp. one that is an important part of its nature: Self-confidence is a rare...
Read more >
Attribute - Definition, Meaning & Synonyms - Vocabulary.com
An attribute is a quality or characteristic given to a person, group, or some other thing. Your best attribute might be your willingness...
Read more >
Attribute definition and meaning | Collins English Dictionary
An attribute is a quality or feature that someone or something has. Cruelty is a normal attribute of human behavior. Synonyms: quality, point,...
Read more >

github_iconTop Related Medium Post

No results found

github_iconTop Related StackOverflow Question

No results found

github_iconTroubleshoot Live Code

Lightrun enables developers to add logs, metrics and snapshots to live code - no restarts or redeploys required.
Start Free

github_iconTop Related Reddit Thread

No results found

github_iconTop Related Hackernoon Post

No results found

github_iconTop Related Tweet

No results found

github_iconTop Related Dev.to Post

No results found

github_iconTop Related Hashnode Post

No results found