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.
Answer from svidgen on Stack ExchangeLean 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.
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)
c# - List of Objects To Json String - Stack Overflow
How to create a list of map objects within a JSON object using for....in loop
data structures - How to represent a set in JSON? - Software Engineering Stack Exchange
How can I turn JSON String into a list of objects based on number of items. - Unity Engine - Unity Discussions
The second is almost correct:
Copy{
"foos" : [{
"prop1":"value1",
"prop2":"value2"
}, {
"prop1":"value3",
"prop2":"value4"
}]
}
The first example from your question,
Copyfoos: [
foo: { ... },
foo: { ... }
]
is in invalid syntax. You cannot have object properties inside a plain array.
The second example from your question,
Copyfoos: [
{ ... },
{ ... }
]
is right although it is not strict JSON. It's a relaxed form of JSON wherein quotes in string keys are omitted.
Following is the correct one when you want to obey strict JSON:
Copy"foos": [
{ ... },
{ ... }
]
This "Mastering JSON" tutorial by Patrick Hunlock, may help to learn about JSON and this site may help to validate JSON.
Create a list of objects.
List<Person> persons = new List<Person>();
persons.Add(new Person { FirstName = "John", LastName = "Doe" });
// etc
return Json(persons, JsonRequestBehavior.AllowGet);
will return
[{"FirstName":"John", "LastName":"Doe"}, {....}, {....}]
The
return Json()
will actually serialize the object it takes as a parameter. As you are passing in a json string, it's getting double encoded. Create an anonymous object with a property named People, then serialize it. so you can:
return Content(JsonConvert.SerializeObject(new {People=PersonList}))
or
return Json(new {People=PersonList});
Well, you can't. As you said, you can represent arrays and dictionaries. You have two choices.
Represent the set as an array. Advantage: Converting from set to array and back is usually easy. Disadvantage: An array has an implied order, which a set doesn't, so converting identical sets to JSON arrays can create arrays that would be considered different. There is no way to enforce that array elements are unique, so a JSON array might not contain a valid set (obviously you could just ignore the duplicates; that's what is likely to happen anyway).
Represent the set as a dictionary, with an arbitrary value per key, for example 0 or null. If you just ignore the values, this is a perfect match. On the other hand, you may have no library support for extracting the keys of a dictionary as a set, or for turning a set into a dictionary.
In my programming environment, conversion between set and array is easier (array to set will lose duplicate values, which either shouldn't be there, or would be considered correct), so for that reason I would go with arrays. But that is very much a matter of opinion.
BUT: There is a big fat elephant in the room that hasn't been mentioned. The keys in a JSON dictionary can only be strings. If your set isn't a set of strings, then you only have the choice of using an array.
Don't try to represent sets in JSON. Do it when parsing the data instead.
Your JSON data should have a schema which specifies which fields should be treated as a set, or you may have a metadata embedded in the JSON data itself that describes when a list should be treated as a set (e.g. {"houses": {"_type": "set", "value": [...]}}) or with a naming convention.
Note that according to JSON standard, a JSON object can have duplicate keys. ECMA-404 wordings:
Objects
[...] The JSON syntax does not impose any restrictions on the strings used as names, does not require that name strings be unique, and does not assign any significance to the ordering of name/value pairs. These are all semantic considerations that may be defined by JSON processors or in specifications defining specific uses of JSON for data interchange.
AFAICD, nothing in the spec forbids non unique names, and there are many JSON parser implementations that can parse non unique object names. RFC 7159 discourages non unique names for interoperability, but specifically don't forbid it either, and goes on to list how various parsers have been seen handling non unique object names.
And ECMA 404 also doesn't require that array ordering be preserved:
Arrays
The JSON syntax does not define any specific meaning to the ordering of the values. However, the JSON array structure is often used in situations where there is some semantics to the ordering.
This wording allows applications to use arrays to represent sets if they so choose.
Let me prefix this by saying I am very new to all this so any help would be so very appreciated - i've been trying to crack this all day and it's been a real struggle. Im making this webapp in ASP.NET core btw. So I've managed to call the twitter api and return back some tweets as JSON depending on a search query. I am then trying to deserialize these into C# objects (using the Tweet class). I then want to pass these objects through as a list to the view for it to render them all out But I just can't seem to get it to work.
I am trying to put desrialize the JSON that comes back into Tweet objects and put them into a ViewModel and then pass the viewmodel to the view. This is what comes back from the API call so I know thats working ok. This is what the Tweet class looks like. The SocialMediaType property is a class in itself, and just has two properties on it which are an Id and name which are given default values as they will always be the same. The error pageI am learning Python, and in particular, working with JSON and sqlite in Python. Ultimately I plan to use Python to load the JSON into a sqlite database.
Here is the question: Is there a way in to list all of the keys from a JSON file (not from a string) using Python? I want a list of all of the keys so I can determine what columns I will need/use in my sqlite table(s), without having to manually read the file and make a list.
BTW, this is something along the lines of using INFORMATION_SCHEMA.COLUMNS in SQL Server, or the FINDALL in Python for XML.
All of this is for personal learning, so I'm not looking to use other technologies, I'm sticking to Python, JSON, and sqlite on purpose.