Alves Gustavo
Alves Gustavo

Reputation: 85

I would like to put a list in an object variable

Something like :

departement = {
  'departement :': [str(x) for x in depart_noms],
  'formation': [str(x) for x in formations]
}

I want to do this to generate a json file except my data is in arrays

I want to build a struct like:

[{"departement": "Économique",
     "formations": [
           {"nom": "Bachelier en informatique de gestion",
            "modules": [ { "accr": "INAF0001-2",
             "lien": "/cocoon/cours/INAF0001-2.html" },
            { "accr": "INAB0002-1",
              "lien": "/cocoon/cours/INAB0002-1.html" },
             ]}
}]

Is that possible to make in a single object variable for all data ?

Upvotes: 1

Views: 63

Answers (1)

CryptoFool
CryptoFool

Reputation: 23139

Here's an example of your code with some simple lists as additional input:

depart_noms = ['a', 'b', 'c']
formations = ['x', 'y', 'z']
departement = {
  'departement :': [{str(x) for x in depart_noms}],
  'formation': [{str(x) for x in formations}]
}

This is perfectly valid Python, but this leads to a structure that can't be JSON serialized because it contains sets (due to the curly braces), which can't be represented in JSON. If you try to execute json.dumps(departement), you'll get the error:

TypeError: Object of type set is not JSON serializable

If instead, your code is this:

import json

depart_noms = ['a', 'b', 'c']
formations = ['x', 'y', 'z']
departement = {
  'departement :': [str(x) for x in depart_noms],
  'formation': [str(x) for x in formations]
}

print(json.dumps(departement))

Your resuilt will be this:

{"departement :": ["a", "b", "c"], "formation": ["x", "y", "z"]}

I'm just taking a stab at this somehow answering your question. If not, then please provide more information to better define what your problem is.

Upvotes: 1

Related Questions