0

I would like to generate a json file from data retrieved in an api request and another json file. The problem is that in my generated json file, the braces are surrounded by double quotes and I also have "\n" and "\r" everywhere. Do you have a solution to generate a json file correctly?

A piece of my python code:

def write_json(data, filename='data.json'):
    with open(filename, 'w', encoding='utf-8') as wf:
        json.dump(data, wf, ensure_ascii=False, indent=4)

# JSON file to fetch IDs
with open('sast-projects.json', 'r', encoding='utf-8') as f:
    projects = json.load(f)

with open('data.json') as json_file:
    data = json.load(json_file)
    temp = data['data']
    
    for project in projects:
        result_detail = requests.get(url_detail + str(project['id']), headers=header_detail)
        temp.append(result_detail.text)
        write_json(data)

And an example of my outpout (data.json):

{
    "data": [
        "{\r\n  \"id\": 12,\r\n  \"teamId\": 34,\r\n  \"owner\": \"Some text\",\r\n  \"name\": \"Some text\"\r\n    }\r\n  ]\r\n}",
        "{\r\n  \"id\": 98,\r\n  \"teamId\": 65,\r\n  \"owner\": \"Some text\",\r\n  \"name\": \"Some text\"\r\n    }\r\n  ]\r\n}"
    ]
}

1 Answer 1

3

Change result_detail.text to result_detail.json(). You're trying to store the raw json string instead of a json object, which is causing double encoding issues.

Sign up to request clarification or add additional context in comments.

3 Comments

Thank you! I changed this. And now I've this error "TypeError: Object of type method is not JSON serializable". Do you have a solution for me?
Sounds like there is some value in data that is a method. If it should be what is returned from that method, you may have forgotten the () when calling it to set that value
Yup, I screwed that up- json is a method and not a property like text is. So turning it to result_detail.json() should resolve it. I've updated my answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.