Parsing JSON object changes order - php

For some odd reason, when I parse my JSON object being send via AJAX, it throws the object out of order.
$.post('get_notes', note_data, function(data){
var notes_obj = $.parseJSON(data);
});
When I console.log data, this is what is returned:
{"502":{"text":"First Response","user_name":"Admin","date":"11-12-2013 9:21"},
"509":{"text":"Second Response","user_name":"Admin","date":"11-12-2013 9:22"},
"508":{"text":"Third Response","user_name":"Admin","date":"11-12-2013 9:24"},
"504":{"text":"Fourth Response","user_name":"Admin","date":"11-12-2013 9:24"}}
This is the correct order. Notice the dates are properly ascending.
When I console.log notes_obj, this is what it returns:
502: Object
504: Object
508: Object
509: Object
For some reason, $.parseJSON() decided to re-order the output by id, and not by date which is what I need.
Any idea why this is happening?

The objects defined by JSON have no order to their properties at all, so it's perfectly acceptable for something to serialize the properties in any order.
The following are exactly identical objects in JSON:
{
"question": "Life, the Universe, and Everything",
"answer": 42
}
{
"answer": 42,
"question": "Life, the Universe, and Everything"
}
In the comments you asked
How do I fix it?
You stop relying on the order of something that is not defined to have any order. You could, for instance, reformat your response so it's an array, because arrays have order:
[
{ "key": "502", "text": "First Response", "user_name": "Admin", "date": "11-12-2013 9:21" },
{ "key": "504", "text": "Fourth Response", "user_name": "Admin", "date": "11-12-2013 9:24" },
{ "key": "508", "text": "Third Response", "user_name": "Admin", "date": "11-12-2013 9:24" },
{ "key": "509", "text": "Second Response", "user_name": "Admin", "date": "11-12-2013 9:22" }
]
Now instead of an object with various keys, you have an array of objects, where each object has a key property (and the other information).

Related

I want a more consolidate json format

I am getting json array after getting applying query logic.
[
{
"id": "3",
"diag_name": "LT Diagnostics",
"test_name": "Alk PO4",
"booking_date": "2018-05-20"
},
{
"id": "3",
"diag_name": "LT Diagnostics",
"test_name": "CRP",
"booking_date": "2018-05-20"
},
{
"id": "4",
"diag_name": "Seepz Diagnostics",
"test_name": "Alk PO4",
"booking_date": "2018-05-21"
}
]
But i want a more justified json array written below.
[
{
"diag_name": "LT Diagnostics",
"test_name": [
{
"id": "3",
"name" : "Alk PO4"
},
{
"id": "3",
"name" : "CRP"
}
],
"booking_date": "2018-05-20"
},
{
"diag_name": "Seepz Diagnostics",
"test_name": [
{
"id": "4",
"name" : "Alk PO4"
}
],
"booking_date": "2018-05-21"
},
]
I am not getting it,How to do in php. I want a more consolidate json format.
Have you tried changing your SQL query to group by diag_name and booking_date? That would be the first step I’d employ to get the outer data.
Formatting the data in the nested manner you’re after could be a function of whatever record serializer you’re using — does it support nested JSON as a return type, or only flat JSON as your example return value shows?
If the record set -> JSON serializer only ever returns flat data, the comments above are correct that you will have to write your own formatter to change the shape of the JSON yourself...
The accepted answer of this other question may be of help:
Create multi-level JSON with PHP and MySQL
I'm not a PHP guy but this is a typical scenario to use functional programming by means of the monad Map.
Looking online I've found this article that could help you.
Changing datasource output is not always (seldom indeed) a viable option.
Enjoy coding

Multidimensional array JSON PHP iteration

Here is my JSON file which is called (inventory.json). How do I parse the json so I can get all of the inventory's tag_name in the "Descriptions" array? Since the Inventory array's classid points out to the description's id/classid, it seems possible to get each of the inventory's tag from the description but I have no idea to do it.
I read something about recursive array iterator and for each but I have no idea which one is appropriate in this circumstance. I am very new here so please be kind! Thank you.
{
"Inventory": {
"7905269096": {
"id": "7905269096",
"classid": "771158876",
"instanceid": "782509058",
"amount": "1",
"pos": 1
},
"7832200468": {
"id": "7832200468",
"classid": "626495772",
"instanceid": "1463199080",
"amount": "1",
"pos": 2
},
"7832199378": {
"id": "7832199378",
"classid": "626495770",
"instanceid": "1463199082",
"amount": "1",
"pos": 3
},
"Descriptions": {
"771158876": {
"classid": "771158876",
"instanceid": "782509058",
"tags": [{
"tag_name": "unique",
"name": "standard"
}]
}
}
}
}
Your JSON string is invalid, but hopefully this answer will lead you on the right path to your desired result.
First, make it into a PHP array:
$jsonArray = /* your json array */;
$phpArray = json_decode($jsonArray, true);
Then you can iterate through one of the arrays (the "Inventory" one) and find the relevant tag name:
//Create a new array to hold the key=>value data
$combined = [];
foreach($phpArray["Inventory"] as $i => $v){
//Find the relevant key in the Descriptions array and
//push this information information to the $combined array
$combined[$i] = $phpArray["Descriptions"][$i]["tags"]["tag_name"];
/* The above is essentially the same as
$combined["7905269096"] = "unique"; */
}
Then, $combined will be a key/value array where the key is the ID (e.g. "7905269096") and the value will be the tag name (e.g. "unique").

am charts json from field to field

Part of the script says from field to field which is to do with this. Here's my JSON pulling info from my database, value 1 is amount, value 2 is time
[{
"date": "2014-12-09",
"value1": 367,
"value2": 03:06:00
}, {
"date": "2014-12-09",
"value1": 367,
"value2": 03:06:00
}]
That's my data, this is part of the script that wants me to map it? :S
dataSet.fieldMappings = [{
fromField: "valu1",
toField: "value2"
}, {
fromField: "volume",
toField: "volume"
}];
I only have 3 fields don't I? Sorry for a vague question, I just don't understand.
The fieldMapping maps the JSON-fields with the valueField specified in the graph-properties.
I guess what you want to do is something like this:
[{
"date": "2014-12-09 03:06:00",
"value": 367
}, {
"date": "2014-12-09 03:07:00",
"value": 673
}]
Note that i put the time into the date-field and changed the second date and value to be different from the first. (I think two similar datapoints won't work)
For this dataset your mapping should look like this:
dataSet.fieldMappings = [{
fromField: "value", // this is the JSON-field
toField: "valueMapped" // the graph will search for this field - see below
}];
To find the data, the graph needs to know the mapped field:
"graphs": [{
"valueField": "valueMapped"
}];
Now one last step for the correct use of the "date"-field:
"dataDateFormat": "YYYY-MM-DD JJ:NN:SS",
"categoryField": "date"

"Nested" array within db response using Codeigniter

I am trying to create a "nested" array within an object that I am returning from a database.
I can have more than one footnote per "thing".
This is what I am currently getting back:
JSON
{
"data": [{
"id": "123",
"type": "foo",
"color": "bar",
"footnote_id": "1",
"footnote_text": " Footnote one"
}]
}
Here is the result I'm trying to generate:
JSON
{
"data": [{
"id": "123",
"type": "foo",
"color": "bar",
"footnotes": [{
"footnote_id": "1",
"footnote_text": " Footnote one"
},
{
"footnote_id": "2",
"footnote_text": "Footnote two"
}]
}]
}
I have a footnotes table that has all kinds of footnotes (footnote_id and such).
I have a type table that has all kinds of things in it (type_id and such).
I also have a type_footnotes table that only has two columns: type_id and footnote_id
I'm not sure how to create the footnotes property of the response object - then display the results within that array.
Thank you for your time!
EDIT
Here is the query - I thought I had posted this as well. My apologies.
PHP
public function get_thing($type_id) {
$this->db->select('type.type_id, type.type, type.type_color');
$this->db->join('footnotes', 'footnotes.footnote_id, footnotes.footnote_text');
$this->db->join('type_footnotes, type_footnotes.type_id = type.type_id');
$query = $this->db->get_where('type', array('type.type_id' => $type_id), 1);
if ($query->num_rows() > 0) {
return $query->result();
}
}
Remove the limit, and post here what do you get as result :
$query = $this->db->get_where('type', array('type.type_id' => $type_id));

Json Traverse Problem, not able to traverse values

I m getting the below return from ajax call but not able to traverse it please please help.
{
"1": {
"tel1": null,
"status": "1",
"fax": "",
"tel2": null,
"name": "sh_sup1",
"country": "Anguilla",
"creation_time": "2010-06-02 14:09:40",
"created_by": "0",
"Id": "85",
"fk_location_id": "3893",
"address": "Noida",
"email": "sh_sup1#shell.com",
"website_url": "http://www.noida.in",
"srk_main_id": "0"
},
"0": {
"tel1": "Ahemdabad",
"status": "1",
"fax": "",
"tel2": "Gujrat",
"name": "Bharat Petro",
"country": "India",
"creation_time": "2010-05-31 15:36:53",
"created_by": "0",
"Id": "82",
"fk_location_id": "3874",
"address": "THIS is test address",
"email": "bp#india.com",
"website_url": "http://www.bp.com",
"srk_main_id": "0"
},
"count": 2
}
You can do it very easily:
for(i = 0; i < msg.count; i++) {
alert(msg[i]['name']);
}
But the structure of your JSON object is not that good for several reasons:
It does not reflect the structure of the actual data
With this I mean, that you actually have an array of objects. But in your JSON object the elements of the array are represented as properties of an object.
You have invalid JavaScript object property names.
Properties for objects in JavaScript are not allowed to start with numbers. But with msg = { "1": {...}} you have a number as property.
Fortunately it is not that bad because you can access this property with "array like" access msg["1"] (instead of the "normal way", msg.1). But I would consider this as bad practice and avoid this as much as possible.
Hence, as Matthew already proposes, it would be better to remove the count entry from the array on the server side, before you sent it to the client. I.e. you should get a JSON array:
[{
"tel1": "Ahemdabad",
"status": "1",
// etc.
},
{
"tel1": null,
"status": "1",
// etc.
}]
You don't need count as you can get the length of the array with msg.length and you can traverse the array with:
for(var i in msg) {
alert(msg[i].name);
}

Categories