I'm using built-in functionality to create JSON string in Flash app.
Here example of my source code
objStr = JSON.stringify(
{
version:"1.0",
skin:"white",
palette:{dataColor:"#0397d6",negativeDataColor:"#d40000",toolbarColor:"#056393"}
});
I have a problem. Every time I've started my app (not executing createJSON function), I have different member order in JSON string as result.
For example:
{"version":"1.0","palette":{"negativeDataColor":"#d40000","dataColor":"#0397d6","toolbarColor":"#056393"},"skin":"white"}
or
{"palette":{"negativeDataColor":"#d40000","toolbarColor":"#056393","dataColor":"#0397d6"},"version":"1.0","skin":"white"}
How can I fix it.
JSON objects are unordered, see JSON.org:
JSON is built on two structures:
A collection of name/value pairs. In various languages, this is
realized as an object, record, struct, dictionary, hash table, keyed
list, or associative array. An object is an unordered set of name/value pairs
An ordered list of values. In most languages, this is realized as an
array, vector, list, or sequence. An array is an ordered collection of values.
Order really doesn't matter since you should be retrieving the values by the key rather than iterating over them.
Related
I Have a use case, where I generate a hash of a JSON object created in java initially and insert the hash and JSON object into the Postgres table as String and jsonb respectively.
I need to validate the JSON object saved initially in regular intervals, During that I fetch the JSON object from Postgres which is stored in jsonb and generate a hash out of it and compare it with the hash generated initially. Both are different now.
The reason is initially when data was inserted order of parameters was different in JSON Object at retrieval the order is different. Ending up generating 2 different hash for the same data.
Please suggest.
Use json type instead of jsonb per JSON:
Because the json type stores an exact copy of the input text, it will preserve semantically-insignificant white space between tokens, as well as the order of keys within JSON objects. Also, if a JSON object within the value contains the same key more than once, all the key/value pairs are kept. (The processing functions consider the last value as the operative one.) By contrast, jsonb does not preserve white space, does not preserve the order of object keys, and does not keep duplicate object keys. If duplicate keys are specified in the input, only the last value is kept.
I am making a request to an API that sometimes returns an array of simple JSON objects, which I am parsing with a simple "for i in count" loop, where I use SwiftyJSON to append json[i]["city"]. For example:
[{"city":"Lakefront","code":"NEW","country":"United States","municipality":"New Orleans","isChild":false,"hasChild":false},
{"city":"Auckland - Auckland International Airport","code":"AKL","country":"New Zealand","municipality":"Auckland","isChild":false,"hasChild":false},
{"city":"Blenheim","code":"BHE","country":"New Zealand","municipality":"Blenheim","isChild":false,"hasChild":false}]
However, in certain cases, the API will return an object with multiple pairs of keys and object values, which I am having trouble parsing with SwiftyJSON. For example:
{"2":{"city":"New York","code":"NYC","country":"United States","municipality":"New York","isChild":false,"hasChild":true},
"32":{"city":"John F. Kennedy - NY","code":"JFK","country":"United States","municipality":"New York","isChild":true,"hasChild":false},
"414":{"city":"LaGuardia - NY","code":"LGA","country":"United States","municipality":"New York","isChild":true,"hasChild":false}}
In this second case, is there a way to loop through the first object with SwiftyJSON, and get the object value noting that I will not know the ID (2, 32, 414) in advance?
Thanks!
In your first case you have an array of dictionaries. In the second case you have a dictionary of dictionaries. I haven't used SwiftyJSON in long enough that I don't remember how it works, but that should be enough to get you going.
I have a little dilema. I have a backend/Frontend Application that comunicates with a JSON based REST Api.
The backend is written in PHP(Symfony/jmsserializer) and the Frontend in Dart
The communication between these two has a little Problem.
For most List Data the backend responds with a JSON like
[{"id":1,...},{"id:2,....}]
But for some it responds with
{"0":{"id":1,...}, "1":{"id:2,....}}
Now my Question is should the backend respond with the later at all or only with the first?
Problem
You usually have a list of objects. You sometimes get an object with sub-objects as properties.
Underlying issue
JS/JSON-Lists are ordered from 0 upwards which means that if you have PHP-Array which does not respect this rule json_encode will output a JS/JSON-Object instead using the numeric indices as keys.
PHP-Arrays are ordered maps which have more features that the JSON-Lists. Whenever you're using those extra features you won't be able to translate directly into JSON-Lists without loosing some information (ordering, keys, skipped indices, etc.).
PHP-Arrays and JSON-Objects on the other hand are more ore less equivalent in terms of features and can be correctly translated between each other without any loss of information.
Occurence
This happens if you have an initial PHP-Array of values which respects the JS/JSON-List rules but the keys in the list of objects are modified somehow. For example if you have a custom indexing order {"3":{}, "0":{}, "1":{}, "2":{}} or if you have (any) keys that are strings (ie. not numeric).
This always happens if you want to use the numeric id of the object as the numeric index of the list {"123":{"id": 123, "name": "obj"}} even if the numeric ids are in ascending order... so long as they are not starting from 0 upwards it's not a json-list it's a json-object.
Specific case
So my guess is that the PHP code in the backend is doing something like fetching a list of objects but its modifying something about it like inserting them by (string) keys into the array, inserting them in a specific order, removing some of them.
Resolution
The backend can easily fix this by using array_values($listOfObjects) before using json_encode which will reindex the entire list by numeric indices of ascending value.
Arrays and dictionaries are two separate types in JSON ("array" and "object" respectively), but PHP combines this functionality in a single array type.
PHP's json_encode deals with this as follows: an array that only contains numeric keys ($array = ['cat', 'dog']) is serialized as JSON array, an associative array that contains non-numeric keys ($array = ['cat' => 'meow', 'dog' => 'woof']) is serialized as JSON object, including the array's keys in the output.
If you end up with an associative array in PHP, but want to serialize it as a plain array in JSON, just use this to convert it to a numerical array before JSON encoding it: $array = array_values($array);
I have a data which are object array. It contains object arrays in a tree structure. I use JSON.stringify(myArray) but the data still contain array because I see [] inside the converted data.
In my case, I want all the data to be converted into json object not array regarding I need to used the data on TreeTable of SAPUI5.
Maybe I misunderstand. Please help me clear.
This is the example of the data that I got from JSON.stringify.
[{"value":{"Id":"00145E5BB2641EE284F811A7907717A3",
"Text":"BI-RA Reporting, analysis, and dashboards",
"Parent":"00145E5BB2641EE284F811A79076F7A3","Type":"BMF"},
"children":[{"value":{"Id":"00145E5BB2641EE284F811A7907737A3",
"Text":"WebIntelligence_4.1","Parent":"00145E5BB2641EE284F811A7907717A3",
"Type":"TWB"},"children":[{"value":{"Id":"00145E5BB2641EE284F811A7907757A3",
"Text":"Functional Areas","Parent":"00145E5BB2641EE284F811A7907737A3","Type":"TWB"},
"children":[{"value":{"Id":"00145E5BB2641EE284F811A7907777A3",
"Text":"CHARTING","Parent":"00145E5BB2641EE284F811A7907757A3","Type":"TWB"},
"children":[{"value":{"Id":"001999E0B9081EE28AB706BE26631E93",
"Text":"Drill","Parent":"00145E5BB2641EE284F811A7907777A3","Type":"TWB"},
"children":[{"value":{"Id":"001999E0B9081EE28AB706BE26633E93",
"Text":"[AUTO][ACCEPT] Drill on charts DHTML","Parent":"001999E0B9081EE28AB706BE26631E93",
"Type":"TWB","Ref":"UT_WEBI_CHARTS_DRILL_HTML"}},{"value":{"Id":"001999E0B9081EE28AB706BE26635E93",
"Text":"[AUTO][ACCEPT] Drill on charts JAVA","Parent":"001999E0B9081EE28AB706BE26631E93",
"Type":"TWB","Ref":"UT_WEBI_CHARTS_DRILL_JAVA"}}]},...
The output that I want shouldn't be array of object but should be something like...
{{"value":{
"Id":"00145E5BB2641EE284F811A7907717A3",
"Text":"BI-RA Reporting, analysis, and dashboards",
"Parent":"00145E5BB2641EE284F811A79076F7A3","Type":"BMF"},
"children":{
{"value":{
"Id":"00145E5BB2641EE284F811A7907737A3",
"Text":"WebIntelligence_4.1",
"Parent":"00145E5BB2641EE284F811A7907717A3",
"Type":"TWB"},
"children":{
{"value":{
"Id":"00145E5BB2641EE284F811A7907757A3",
"Text":"Functional Areas",
"Parent":"00145E5BB2641EE284F811A7907737A3",
"Type":"TWB"},...
JSON.stringify merely converts JavaScript data structures to a JSON-formatted string for consumption by other parsers (including JSON.parse). If you want it to stringify to a different value, you must change the source data structures first.
However, it seems that this can't be represented as anything other than an array because you have duplicate keys (i.e. value appears more than once). That would not be valid for a JavaScript object or a JSON representation of such.
I think what you want is
JSON.stringify(data[0]);
or perhaps
JSON.stringify(data[0].value);
where data is the object you passed in the question
I am tinkering with firebase and curious about the data structure. Browsing to my database, firebase allows me to modify the structure and data in my database. But it seems that firebase only supports objects (and dictionaries for lists).
I want to know if arrays are supported. I would also like to know if dictionary items can be named with integers - the firebase interface only inserts strings as names which makes me concerned about ordering records.
Here is a sample of json created through firebase interface:
{
"dg":{
"users":{
"rein":{
"searches":{
"0":{
"urls":"http://reinpetersen.com,http://www.reinpetersen.com",
"keyphrases":"rein petersen,reinsbrain,programmer turned kitesurfer"
}
}
},
"jacqui":{
"searches":{
"0":{
"urls":"http://www.diving-fiji.com,http://diving-fiji.com",
"keyphrases":"diving marine conservation, diving fiji"
}
}
}
},
"crawl_list":{
"1":{
"urls":"http://www.diving-fiji.com,http://diving-fiji.com",
"keyphrases":"diving marine conservation, diving fiji"
},
"0":{
"urls":"http://reinpetersen.com,http://www.reinpetersen.com",
"keyphrases":"rein petersen,reinsbrain,programmer turned kitesurfer"
}
}
}
}
Obviously, for my lists, I want the dictionary item names to be integers so i can ensure sorting is correct.
You can save arrays into Firebase. For example:
var data = new Firebase(...);
data.set(['x', 'y', 'z']);
Javascript Arrays are essentially just objects with numeric keys. When retrieving data, we automatically detect when a Firebase object has only numeric keys, and we return an array if that is the case.
Note that for storing a list of data to which many people can append, an array is not a good choice, as multiple people writing to the same index in the array can cause conflicts. Instead, we have a "push" function which creates a chronologically-ordered unique ID for your data.
Also, if you're intending to use the array as a way of ordering data, there's a better way to do that using our priorities. See the docs.
The Firebase docs have a pretty good section on how to order your data: Ordered Data.
Just like JSON fields, Firebase fields can only be named with strings. It sounds like what you're looking for is setWithPriority(), which attaches sortable priority data to your fields, or push(), which is guaranteed to give your fields unique names, ordered chronologically. (More on lists and push() here.)
You can also push() or set() arrays. For example,
new Firebase("http://gamma.firebase.com/MyUser").push(["cakes","bulldozers"]);
results in a tree like you'd expect, with MyUser receiving a uniquely named child who has children "0":"cakes" and "1":"bulldozers".