2

I'm using Flask Restful to create a simple API that returns a JSON in a get Response. All my methods are all good, my problem is in a little detail in the response result, because the JSON is actually coming as a string and I don't understand what I need to do.

The problem happens when I convert the python dict with json.dumps()

I've tried to do it without the json.dumps() method and my result comes in the desired format but not an actual valid JSON.

Here is my code:

class People(Resource):
def get(self):
    handle =  open("json_test.txt", "r")
    txt = handle.read()
    json  = self.names(txt)
    return jsonify({'result': json})

    def names(self, data):
        json.loads(data)
        print(data)
        ids = []
        names = []
        for n in data['people']:
            print(n)
            id = n['id']
            name = n['name']
            ids.append(id)
            names.append(name)

        test_list = []
        counter = 0
        for item in names:
            test_item = {"id": ids[counter], "name": names[counter]}
            test_list.append(test_item)
            counter = counter+1

        names_json = json.dumps(test_list, ensure_ascii=False)
        print(names_json)
        return names_json

This is my desired output:

{
  "result": {
    "people": [
      {
        "id": "12345",
        "nome": "Felipe"
      },
      {
        "id": "54321",
        "nome": "Jean"
      }
    ]
  }
}

But I'm getting this actual output:

{
result: "{"people": [{"id": "54321", "name": "Felipe"}, {"id": "12345", "name": "Jean"}]}"
}

It's coming: result = "{json}", a string and not the actual json, but the data inside the double quote is a valid json.

sirfelipe
  • 31
  • 6

1 Answers1

0

Would this work?

return names_json["result"]
user3738936
  • 936
  • 8
  • 22
  • No, it's like the data inside the result becomes a string and not a dict/list. When I try to remove the return jsonify({'result': json}) line to: return jsonify(json) it gives me a broken json with \ separating each value. – sirfelipe Jul 03 '19 at 17:50