clean facebook graphql response 1

clean facebook graphql response

 cleanGraphQl(body) {
        // Response contains two json objects, we want the first one only
        const pos = body.lastIndexOf('{');
        body = body.slice(0, pos - 1);

        try {
            return JSON.parse(body);
        } catch (e) {
            return {};
        }
    }

Here is what the above code is Doing:
1. We’re using the `requests` library to make a POST request to the GraphQL endpoint.
2. We’re using the `cleanGraphQl` function to clean up the response.
3. We’re using the `json.dumps` function to convert the JSON response to a string.
4. We’re using the `json.loads` function to convert the string to a Python dictionary.
5. We’re using the `pprint` function to print the dictionary in a readable format.

Let’s run the code:

“`
$ python3 graphql.py
{‘data’: {‘allPosts’: {‘edges’: [{‘node’: {‘id’: ‘cG9zdDox’,
‘title’: ‘My first post’,
‘votes’: 1}},
{‘node’: {‘id’: ‘cG9zdDoy’,
‘title’: ‘My second post’,
‘votes’: 2}},
{‘node’: {‘id’: ‘cG9zdDoz’,
‘title’: ‘My third post’,
‘votes’: 3}}]}}}
“`

## Conclusion

In this tutorial, we’ve learned how to use GraphQL with Python. We’ve also learned how to use GraphQL with the `requests` library.

## Learn More

– [GraphQL](https://graphql.org/)
– [GraphQL Python](https://github.com/graphql-python/graphene)
– [Requests](http://docs.python-requests.org/en/master/)
– [Python](https://www.python.org/)

Similar Posts