JSON.parse() how to prevent alphabet sorting of keys - json

I have JSON string that I retrieve from server:
"{ \"id\": 1, \"name\": \"Bill\", \"fields\": [\"a\", \"b\"] }"
When I do JSON.parse() then it sorts keys in alphabetical order:
{ fields: ["a", "b"], id: 1, name: "Bill" }
How can I prevent this sorting?

Official specification (json.org) states:
"An object is an unordered set of name/value pairs."
The order or properties should not matter, your application should have same results regardless. If you design your application around this order, it is a mistake.

Related

Сonvert dict or json formats with nested objects into string

Now I have a string in format dict but as i can guess its a json format its look like:
{
"gid":"1201400250397201",
"memberships":[
"can be nested objects",
...
],
"name":"Name of task",
"parent":{
"gid":"1201400250397199",
"name":"name of parent task"
},
"permalink_url":"https://url...."
}
So first question: am i right? I used dumps() from json library but got unicode escape sequences, loads() didnt work for me, i got error "the JSON object must be str, bytes or bytearray, not dict".
Second question: if its not json format, how can i get comfortable view? I did it:
first of all i get dict-line, then I print a dictionary's key:
for key in task:
task
print(task[key])
output:
1201400250397201
[]
Name of task
{'gid': '1201400250397199', 'name': ''name of parent task'}
https://url....
At actually it would be great if I get something like that:
gid: 1201400250397201
name: Name of task
parent_name: 'Name of task' etc
But I dont know how to get it :(
Next question: as you can see for part "parent" (penultimate line) I also get dictionary, how can I extract it and get convenient format?
Or maybe you have your comfortable methods?
Like stated in your error, the object you are working with is already a dictionary. You can print it directly as json with json.dumps:
task = {'gid': '1201400250397201', 'memberships': [{}], 'name': 'Name of task', 'parent': {'gid': '1201400250397199', 'name': 'name of parent task'},'permalink_url': 'https://url....'}
print(json.dumps(task, indent=4))
Setting indent=4 makes it readable and you'll get:
{
"gid": "1201400250397201",
"memberships": [
{}
],
"name": "Name of task",
"parent": {
"gid": "1201400250397199",
"name": "name of parent task"
},
"permalink_url": "https://url...."
}
If you don't want unicode characters to be escaped, add the argument ensure_ascii=False:
print(json.dumps(task, indent=4, ensure_ascii=False))

How to get all the keys from dynamic JSON object using pandas in python

I get a complex JSON response from multiple webservice. I need to get all the keys in various level using python. To use JSON_NORMALISE i need to know the key name. Since i get multiple responses i am not able to give the key name. If i normalize in outer level the json in lower level is not converted into dictionary. It is still in json format.
{'Id': 123,
'oldnumber': 1,
'new number': 8,
'version': 1,
'newversion': 1,
'personList':[{
'id':1,
'name': xyz,
'marks':[{'phy':90,
'che':80
}
{'bot':90,
'zoo':80
},
{'phy':60,
'che':80
}
{'bot':20,
'zoo':80
}
]}
],
'anotherList':[{
'id':1,
'data': xyz,
'some':[{'not':90,
'dot':80
}
{'cot':90,
'pot':80
},
{'ans':60,
'dog':80
}
{'cat':20,
'mat':80
}
]}
]
}
How to read all the key names from the JSON i get from response?
To get all the keys from complex JSON object we can directly iterate through the JSON object with simple python. I got the solution from below link.
Reference - https://towardsdatascience.com/flattening-json-objects-in-python-f5343c794b10
I modified the code a bit and now i am able to get all the keys from JSON
def normalise_json(y):
out = set()
def normalise(x):
if type(x) is dict:
for a in x:
out.add(a)
normalise(x[a])
elif type(x) is list:
for a in x:
normalise(a)
normalise(y)
return out

JDT transform to modify N-th array element

I am trying to apply a JDT transform to a JSON document in order to modify a property in a N-th array element. Is that possible without having to replace the entire element or even the entire array?
{
"array": [
{
name: "A",
value: 0
},
{
name: "B",
value: 3.14
}
]
}
Is there a transform that gets me to the following? I want to alter the 2nd array element and only its "value" property. I don't want to search for it by "name" but rather access by index.
{
"array": [
{
name: "A",
value: 0
},
{
name: "B",
value: 12345678
}
]
}
The challenge
It is easy to do your transform with some libraries in JSON. If your object is called foo, you mainly want to something like foo.array[1].value = "12345678" without any kind of looping.
The JDT way
I found How to use SlowCheetah to transform an array elements in Json config file? which asks
For example, if my base config file has this setting:
{
"Settings" : [1, 2, 3]
}
and I want to transfer it to:
{
"Settings" : [4, 5, 6]
}
The solution by Collin K was
{
"#jdt.replace": {
"#jdt.path": "$.Settings",
"#jdt.value": [4,5,6]
}
}
This seems like you need to actually replace the whole array.
Digging further let me to an open issue of JDT which seems to confirm this assumption.
Disclaimer
I have not used JDT myself, but I have been struggling with nested JSONs of various kinds e.g. with Elasticsearch.
Further references
https://github.com/microsoft/json-document-transforms/wiki/Replace-Transformation
Using jq to update objects within a JSON document if the value corresponding to a given key starts with a specified string - the JQ way I would use

Order of performing sorting on a big JSON object

i have a big json object with a list of "tickets". schema looks like below
{
"Artist": "Artist1",
"Tickets": [
{
"Id": 1,
"Attr2Array": [
{
"Att41": 1,
"Att42": "A",
"Att43": null
},
{
"Att41": 1,
"Att42": "A",
"Att43": null
},
],
.
.
.
(more properties)
"Price": "20",
"Description": "I m a ticket"
},
{
"Id": 4,
"Attr2Array": [
{
"Att41": 1,
"Att42": "A",
"Att43": null
},
{
"Att41": 1,
"Att42": "A",
"Att43": null
},
],
.
.
.
.
(more properties)
"Price": "30",
"Description": "I m a ticket"
}
]
}
each item in the list has around 25-30 properties (some simple types, and others complex array as nested objects)
i have to read the object from an api endpoint and extract only "ID" and "Description" but they need to be sorted by "Price" which is an int for example
In what order shall i proceed with this data manipulation
Shall i use the json object, deserialised it into another object with just those 2 properties (which i need) and THEN perform sort "asc" on the "Price"?
Please note that after i have the sorted list i will have to convert it back to a json list because the front end consumes a json after all.
What i dont like about this approach is the cycle of serialisation and deserialisation that happens
or
I perform a sort on the json object first (using for example a binary/bubble sort) and then use the object to create a strongly typed (deserialised) object with just those 2 properties and then serialise it back to pass to the front end
I dont know how performant the bubble sort will be and if at all i will get any gain in performance for large chunks of data processing.
I also need to keep in mind that this implementation can take into account other properties like "availabilitydate" because at a later date, this front end could add one more filter like "availabilitdate" asc
any help is much appreciated
thanks
You can deserialize your JSON string (or file) using the Microsoft System.Web.Extensions and JavaScriptSerializer.DeserializeObject.
First, you must have classes associated to your JSON. To create classes, select your JSON sample data and, in Visual Studio, go to Edit / Paste Special / Paste JSON As Classes.
Next, use this sample to deserialize a JSON string to typed objects, and to sort all Tickets by Price property using Linq.
String json = System.IO.File.ReadAllText(#"C:\Data.json");
var root = new System.Web.Script.Serialization.JavaScriptSerializer().Deserialize<Rootobject>(json);
var sortedTickets = root.Tickets.OrderBy(t => t.Price);

How do you represent a JSON array of strings?

This is all you need for valid JSON, right?
["somestring1", "somestring2"]
I'll elaborate a bit more on ChrisR awesome answer and bring images from his awesome reference.
A valid JSON always starts with either curly braces { or square brackets [, nothing else.
{ will start an object:
{ "key": value, "another key": value }
Hint: although javascript accepts single quotes ', JSON only takes double ones ".
[ will start an array:
[value, value]
Hint: spaces among elements are always ignored by any JSON parser.
And value is an object, array, string, number, bool or null:
So yeah, ["a", "b"] is a perfectly valid JSON, like you could try on the link Manish pointed.
Here are a few extra valid JSON examples, one per block:
{}
[0]
{"__comment": "json doesn't accept comments and you should not be commenting even in this way", "avoid!": "also, never add more than one key per line, like this"}
[{ "why":null} ]
{
"not true": [0, false],
"true": true,
"not null": [0, 1, false, true, {
"obj": null
}, "a string"]
}
Your JSON object in this case is a list. JSON is almost always an object with attributes; a set of one or more key:value pairs, so you most likely see a dictionary:
{ "MyStringArray" : ["somestring1", "somestring2"] }
then you can ask for the value of "MyStringArray" and you would get back a list of two strings, "somestring1" and "somestring2".
Basically yes, JSON is just a javascript literal representation of your value so what you said is correct.
You can find a pretty clear and good explanation of JSON notation on http://json.org/
String strJson="{\"Employee\":
[{\"id\":\"101\",\"name\":\"Pushkar\",\"salary\":\"5000\"},
{\"id\":\"102\",\"name\":\"Rahul\",\"salary\":\"4000\"},
{\"id\":\"103\",\"name\":\"tanveer\",\"salary\":\"56678\"}]}";
This is an example of a JSON string with Employee as object, then multiple strings and values in an array as a reference to #cregox...
A bit complicated but can explain a lot in a single JSON string.