The second is almost correct:

{
    "foos" : [{
        "prop1":"value1",
        "prop2":"value2"
    }, {
        "prop1":"value3", 
        "prop2":"value4"
    }]
}
Answer from Justin Niessner on Stack Overflow
Top answer
1 of 7
3

Lean towards option 1, as it's a more expected format.

Option 1 works with JSON as it's designed to be used and therefore benefits from what JSON offers (a degree of human readability, which is good for debugging, and straightforward parsing, which is good for limiting entire categories of bugs to begin with).

Option 2 begrudgingly adopts JSON and subverts many of the benefits. If you don't want human readability, use protobuf or something similar... AIWalker's "CSV"-like approach isn't terrible either. It is marginally better (readable) than splitting objects apart and recombining them. But, this is still not as good (readable) as using JSON "as designed".

Also bear in mind, your API responses are also likely going to be gzipped. Most of the repetition in option 1 will be quickly and transparently condensed over the wire.

As an aside, if you're moving a lot of data, also consider JSONL or paginated results. Pagination can be especially helpful for web clients, as it places natural pauses in the processing, providing a degree of "organic" protection against UI lockups.

2 of 7
3

A list of objects is easier to work with. You can use append, map, filter... All the nice things JS Arrays have which manual indexing doesn't. And there's no way to get out of sync, so that's an entire class of bugs gone.

If you're worried about efficiency:

  • Measure (premature optimization is the root of all evil)
  • Consider the list of lists trick AIWalker proposed
  • Consider an outright binary format
  • Make sure gzip is enabled
  • Measure (it's worth saying twice)
๐ŸŒ
RestfulAPI
restfulapi.net โ€บ home โ€บ json โ€บ json array: syntax, nested arrays and examples
JSON Array: Syntax, Nested Arrays and Examples
3 weeks ago - A JSON array is an ordered list of values, written between square brackets with a comma between each value. The values can be strings, numbers, booleans, null, objects or other arrays, and one array may mix them. Arrays matter because almost every API uses them to send lists, such as search results, order lines, tags or map coordinates.
๐ŸŒ
JSON Schema
json-schema.org โ€บ understanding-json-schema โ€บ reference โ€บ array
JSON Schema - array
List validation is useful for arrays of arbitrary length where each item matches the same schema. For this kind of array, set the items keyword to a single schema that will be used to validate all of the items in the array. In the following example, we define that each item in an array is a number:
๐ŸŒ
Codeblogmoney
codeblogmoney.com โ€บ json-example-with-data-types-including-json-array
JSON Example with Data Types Including JSON Array
July 3, 2018 - Valid JSON Data Types String Number Object Array Boolean Null 1. JSON String Example: 1 2 3 4 5 { "firstname": "Tom", "lastname": "Cruise", "occupation": "Actor" } This example shows information about a person, and you know Tom Cruise.
๐ŸŒ
W3Resource
w3resource.com โ€บ JSON โ€บ structures.php
JSON Structures | JSON tutorial | w3resource
An ordered list of values. In various programming languages, it is called as array, vector, list, or sequence. Since data structure supported by JSON is also supported by most of the modern programming languages, it makes JSON a very useful data-interchange format.
Find elsewhere
๐ŸŒ
JAXB
javaee.github.io โ€บ tutorial โ€บ jsonp001.html
Introduction to JSON
JSON defines only two data structures: objects and arrays. An object is a set of name-value pairs, and an array is a list of values. JSON defines seven value types: string, number, object, array, true, false, and null. The following example shows JSON data for a sample object that contains name-value pairs.
๐ŸŒ
JSON
json.org โ€บ example.html
JSON Example
{"web-app": { "servlet": [ { "servlet-name": "cofaxCDS", "servlet-class": "org.cofax.cds.CDSServlet", "init-param": { "configGlossary:installationAt": "Philadelphia, PA", "configGlossary:adminEmail": "ksm@pobox.com", "configGlossary:poweredBy": "Cofax", "configGlossary:poweredByIcon": "/images/cofax.gif", "configGlossary:staticPath": "/content/static", "templateProcessorClass": "org.cofax.WysiwygTemplate", "templateLoaderClass": "org.cofax.FilesTemplateLoader", "templatePath": "templates", "templateOverridePath": "", "defaultListTemplate": "listTemplate.htm", "defaultFileTemplate": "articleTem
๐ŸŒ
YouTube
youtube.com โ€บ watch
List Items from JSON data Creating list with JavaScript from a JSON data file interactive list items - YouTube
List Items from JSON dataLearn JavaScript AJAX JSON codeJavaScript Dynamic Web Pages AJAX 30 Projects APIs JSONJavaScript projects explore JavaScript to conn...
Published: November 7, 2021
๐ŸŒ
JSON Editor Online
jsoneditoronline.org โ€บ home โ€บ datasets โ€บ json-file-example
Exploring the power of JSON: a real-life JSON file example collection
July 25, 2023 - A curated list of awesome JSON Datasets like: climate, crime, food, gaming, government, population, movies, etc.
๐ŸŒ
W3Schools
w3schools.com โ€บ js โ€บ js_json_server.asp
JavaScript Loading JSON
JS Examples JS HTML DOM JS HTML Input JS HTML Objects JS HTML Events JS Browser JS Editor JS Exercises JS Quiz JS Website JS Syllabus JS Study Plan JS Interview Prep JS Certificate ... JSON is often stored in files or returned by calls to web servers.
๐ŸŒ
Python Examples
pythonexamples.org โ€บ python-list-to-json
Python List to JSON
import json a_list = [{'a':1, 'b':2}, {'c':3, 'd':4}] json_string = json.dumps(a_list) print(json_string) ... In this example, we will take a Python List of Lists and convert it to JSON string.
๐ŸŒ
EDUCBA
educba.com โ€บ home โ€บ software development โ€บ software development tutorials โ€บ javascript tutorial โ€บ json array of strings
JSON Array of Strings | How JSON Array of String Works? (Examples)
April 14, 2023 - We have seen how JSON array represents an ordered list of values be it string, numbers, Boolean, or an object. Here as per the topic, we have discussed how array of strings are accessed using for loop, how array value can be deleted, multi dimensional array, a nested array with examples listed above for each.
Address: Unit no. 202, Jay Antariksh Bldg, Makwana Road, Marol, Andheri (East),, 400059, Mumbai
๐ŸŒ
JSONata
docs.jsonata.org โ€บ simple
Simple Queries ยท JSONata
Negative indexes count from the end of the array, for example, arr[-1] will select the last value, arr[-2] the second to last, etc.
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ python-json-to-list
Python Json To List - GeeksforGeeks
April 18, 2026 - The Pandas read_json() method is used to read JSON strings into a DataFrame and then extract the list. In this example, the pd.read_json() method from the pandas library is used to read a JSON-formatted string into a DataFrame.
๐ŸŒ
Polygon
docshield.tungstenautomation.com โ€บ KTA โ€บ en_us โ€บ 7.9.0-ud9cfx6hos โ€บ help โ€บ designer โ€บ All_Shared โ€บ SystemData โ€บ c_dmjsonexamples.html
Examples of data models using JSON sample
You can create a data model for simple JSON string, with strings having nested objects multiple objects, and with array of data. This section provides the examples of data models that are based on sample JSON string.
๐ŸŒ
Reddit
reddit.com โ€บ r/learnprogramming โ€บ how do i make a list of list a json file?
r/learnprogramming on Reddit: How do I make a list of list a JSON file?
April 8, 2022 -

I have a sqlite database were I store my workout exercises. I have been working to get these exercises into a JSON files to send to my website to display graphs using Chartjs.

Going through this article (https://changsin.medium.com/how-to-serialize-a-class-object-to-json-in-python-849697a0cd3) they take two objects and turn them into a JSON output. Like this:

label1 = Label("person", 10, 10, 4, 10)
label2 = Label("car", 20, 20, 5, 11)

image_bboxes = {"image1.jpg": [label1, label2]}

output:
{"version": 1,
"type": "box",
"bounding box":
    {"image1":
        [{"label": "person",
            "x": 10,
            "y": 20
          },
          {"label": "car",
            "x": 10,
            "y": 20
          }
         ]
    }
}

Now I have a list of lists looking like this:

all_exercises = [[planks1, planks2],[bench1,bench2]]

I want to create a JSON output that will allow me to pass it off to my website. Then use JS and Chartjs to display the user selected graph. I can get the graph to do what I want it to do. I don't know how to make the JSON output. I'm not understanding something fundamental when I am using JSON. I just don't know what it is. A book or resource would be greatly appreciated.

My output currently looks like this:

{
  "version": 1,
  "exertest": {
    "second": [
      { //Need's to be labeled PLANK here
        "id": 325,
        "interval": 1,
        "resistance": 0,
        "set_number": 1,
        "workout_id": 58,
        "workout_date": "2022-03-28T06:00",
        "exercise_id": 24,
        "exercise_name": "Plank"
      },
      {
        "id": 326,
        "interval": 1,
        "resistance": 0,
        "set_number": 2,
        "workout_id": 58,
        "workout_date": "2022-03-28T06:00",
        "exercise_id": 24,
        "exercise_name": "Plank"
      },
      {  // Needs to be labeled HIP BRIDGE here
        "id": 327,
        "interval": 15,
        "resistance": 0,
        "set_number": 1,
        "workout_id": 58,
        "workout_date": "2022-03-28T06:00",
        "exercise_id": 25,
        "exercise_name": "Hip Bridge"
      }
    ]
  }
}
Top answer
1 of 2
1
I figured it out. You first have to make sure your list of lists is sorted correctly like this: # find the first exercise of the exercises exercise_id = graph_exercises[0].exercise_id # start a small list big_lst = [] small_lst = [] for i in graph_exercises: # add to small list til exercise changes if i.exercise_id == exercise_id: small_lst.append(i) else: # add small list to big list big_lst.append(small_lst) # start a new small list small_lst = [] exercise_id = i.exercise_id small_lst.append(i) exercises = {"Exercises": big_lst} exercise_col = ExerciseCollection(exercises) json_exercise_col = json.dumps(exercise_col, default=default, indent=1) Then you need a class that will handle the list in a list: ExerciseCollection.py // Create a to_json function and use your list of lists to fill it up //Relative parts of the file are below def to_json(self): to_return = {"version": self.version, "type": self.type} exercises = {} for key, exercises2 in self.exercises2.items(): i_exercises = [] dict_exercise_types = {} for exercise in exercises2: j_exercises = [] k = exercise[0].exercise_name for j in exercise: j_exercises.append(j.__dict__) dict_exercise_types[k] = j_exercises i_exercises.append(dict_exercise_types) exercises[key] = i_exercises to_return["Exercises"] = exercises return to_return That's it. Now on to using the data. Which was not part of my question so will not be answered here.
2 of 2
1
Ah, you want something like data = { "plank": { "field": 123, .... } } Your structure is an array, you want an object instead so you can write data.plank?