0

I have a model like this:

class MyClass(models.Model):
    typea = models.CharField(max_length=128)
    typeb = models.CharField(max_length=128)

If for example, the resulting json from an API is like this:

{
    "count": 75,
    "results": [
    {
        "typea": "This tipe",
        "typeb": "A B type",
        "jetsons": [],
        "data": [
            "https://myurl.com/api/data/2/",
        ],
        "created": "2014-12-15T12:31:42.547000Z",
        "edited": "2017-04-19T10:56:06.685592Z",
    },

I need to parse this result and save typea and typeb into the database, I'm kind of confused on how to do this.

I mean, there is the JSONField on Django, but I don't think that will work for me, since I need to save some specific nested string of the json dict.

Any example or idea on how to achieve this?

I mean, my confusion is on how to parse this and "extract" the data I need for my specific fields.

Thank You

1
  • 1
    Do you need to create a new entry for each typea & typeb in results? If so, just parse it using the json library (great example here w3schools.com/python/python_json.asp) and save it for each key Example: y = json.loads(x) for value in y["results"] a = value["typea"] b = value["typeb"] // do something Commented Jul 10, 2019 at 7:24

1 Answer 1

1

You can always do an import json and use json.load(json_file_handle) to create a dictionary and extract the values you need. All you need is to open the .json file (you can use with open("file.json", "r") as json_file_handle) and load the data.

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

2 Comments

Hi, thanks, but my issue is precisely how can I extract it from the dict, I mean, it's not like many examples around. I mean the process of doing it.
You could save the data from the dictionary as variables, an example @Scircia posted above. Afterwards, you'd need a MyClass.objects.create(typea=a, typeb=b)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.