Create a JSON from a list in Python

Question:

I have a list with a bunch of sentences, very much like below:

["Hello, how are you", "You look great today", "Your shoes are ugly", "Your momma so fat she…"]

I want to use the Azure Cognitive Services API which expects its request to be in this form:

{
  "documents": [
    {
      "language": "en",
      "id": "1",
      "text": "Hello, how are you"
    },
    {
      "language": "en",
      "id": "2",
      "text": "You look great today"
    },
    {
      "language": "en",
      "id": "3",
      "text": "Your momma so fat she..."
    }
  ]
}

I don’t have any clue how to create a nested json from a flat list. I would need to have id be incremented for each element in the list and language be en for every item in the list.

Any help or links would be appreciated

Answers:

Unless I am missing something about your question, it would probably be easiest to just iterate through your array when creating the JSON you need. Python lets you create arrays like:

[something(i) for i in someArray]

For your example you could probably do something like:

yourText = ["There is text", "in this array", "please convert it!"]

yourJSON = {"documents" : [{ "language" : "en", "id" : str(idx + 1), "text": val} for idx, val in enumerate(array)]}
Answered By: Joshua
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.