I'm working with a plugin called (http://michaeleisenbraun.com/columns/) that converts json to tables.
I use the following code:
<script>
$.ajax({
url:'/large-data.json',
dataType: 'json',
success: function(json) {
example2 = $('#example2').columns({
data:json,
});
}
});
</script>
It works well when the json is in brackets, like below:
[
{
"id": 9998,
"isActive": false,
"balance": "$5",
"age": 38,
"eyeColor": "blue",
"name": "Lola Townsend",
"gender": "female",
"company": "...",
"email": "asdf#asdf.com,
"phone": "..."
}
]
But, does not work if the json is not in brackets, like below:
{
"id": 9998,
"isActive": false,
"balance": "$5",
"age": 38,
"eyeColor": "blue",
"name": "Lola Townsend",
"gender": "female",
"company": "...",
"email": "asdf#asdf.com,
"phone": "..."
}
The json response is from other sites, so I will not be able to control whether it does / does not have brackets.
Is there a way to ensure the json returned has brackets each time and if not, that brackets are added?
I tried JSON.parse() and it did not work.
The first one mean it's an array object, the second one is only an object. I don't really get what you are trying to do right now but you can simply ass the object into in array if it's not allready one. something like :
if(!Arrays.isArray(yourObject)) {
var temp = [] ;
temp.push(yourObject);
yourObject= temp;
}
I haven't test it since i don't know what you want to do, but this is the main idea.
Hope it helps !
Nic
You can use regex to check if the code is correct with ^\[|\n*\]$. You should have 2 matches if the first character of the string is [ and the last is ].
You can test here : https://regex101.com/r/Cukwog/1
Related
So I have a JSON file I got from Postman which is returning as an empty object. This is how I'm reading it.
import regscooter from './json_files/reginald_griffin_scooter.json'
const scoot = regscooter;
const CustomerPage = () => {...}
reginald_griffin_scooter.json
{
"success": true,
"result": {
"id": "hhhhhhhhhh",
"model": "V1 Scooter",
"name": "hhhhhhhhhh",
"status": "active",
"availabilityStatus": "not-available",
"availabilityTrackingOn": true,
"serial": "hhhhhhhhhhhh",
"createdByUser": "hhhhhhhhK",
"createdByUsername": "hhhhhhhh",
"subAssets": [
"F0lOjWBAnG"
],
"parts": [
"hhhhhhhh"
],
"assignedCustomers": [
"hhhhhhhhh"
],
"createdAt": "2019-12-03T21:47:26.218Z",
"updatedAt": "2020-06-26T22:05:54.526Z",
"customFieldsAsset": [
{
"id": "hhhhhhh",
"name": "MAC",
"value": "hhhhhhhh",
"asset": "hhhhhhhhhh",
"user": "hhhhhhhhh",
"createdAt": "2019-12-03T21:47:26.342Z",
"updatedAt": "2019-12-11T16:29:24.732Z"
},
{
"id": "hhhhhhhh",
"name": "IMEI",
"value": "hhhhhhh",
"asset": "hhhhhhh",
"user": "hhhhhhhhhh",
"createdAt": "2019-12-03T21:47:26.342Z",
"updatedAt": "2019-12-11T16:29:24.834Z"
},
{
"id": "hhhhhhhhh",
"name": "Key Number",
"value": "NA",
"asset": "hhhhhhhhh",
"user": "hhhhhhhhhhh",
"createdAt": "2019-12-03T21:47:26.342Z",
"updatedAt": "2019-12-11T16:29:24.911Z"
}
]
}
}
The error is that "const scoot" is being shown as an empty object {}. I made sure to save a ton of times everywhere. I am able to read through the imported JSON file in other variables in similar ways, so I don't know why I can't parse this one. I just want to access the JSON object inside this. Also I omitted some information with hhhhh because of confidentiality.
EDIT: The code works, but it still has a red line beneath result when I do:
const scoot = regscooter.result.id;
It would be much more effective if you will provide an example in codesandbox or so.
However at first look it might be a parser issue ( maybe you are using Webpack with missing configuration for parsing files with json extension ), meaning we need more information to provide you with a full answer ( maybe solution ? ).
Have you tried to do the next:
const scoot = require('./json_files/reginald_griffin_scooter.json');
Actually i am pushing data to other system but before pushing i have to change the "key" in the whole JSON. JSON may contain 200 or 10000 or 250000 data.
sample JSON:
{
"insert": "table",
"contacts": [
{
"testName": "testname",
"ContactID": 212121
},
{
"testName": "testname",
"ContactID": 2146354564
},
{
"testName": "testname",
"ContactID": 12312
},
{
"testName": "testname",
"ContactID": 211221
},
{
"testName": "testname",
"ContactID": 10218550
}
]
}
I need to change contacts array Keys. These contacts may be in bulk. So i need to work with this efficiently with minimal complexity.
The above JSON to be converted as below
{
"insert": "table",
"contacts": [
{
"name": "testname",
"phone": 212121
},
{
"name": "testname",
"phone": 2146354564
},
{
"name": "testname",
"phone": 12312
},
{
"name": "testname",
"phone": 211221
},
{
"name": "testname",
"phone": 10218550
}
]
}
here is my code trying by loop
ini_dict = request.data
contact_data = ini_dict['contacts']
for i in contact_data:
i['name'] = i.pop('testName')
print(contact_data)
Please suggest me how can i change the key names efficiently for bulk data. i mean for 50000 lists in contacts. "for loop" will be leading a performance issue. So please let me know the efficient way to achieve this
I dont know how fast you need it to be nor how you are choosing to store your json. One simple solution is just store it as a string and then replace all the instances of your attributes.
# Something like this using a jsonstring
jsonstring.replace("'testName':", "'name':")
jsonstring.replace("'ContactId':", "'phone':")
If you want to do this in bulk you, may need to create some batch process to be able to fetch multiple existing records and make changes at once. I have done this before with the java equivalent of https://pypi.org/project/JayDeBeApi/ but, that was more for modifying existing records in a database.
I've been working with datatables and I'm able to load the datatable using getJson with strongly typed classes etc and it works just great. Until I hit one snag.
There are times I want to populate a datatable with data that "I don't know about" but I always know that it will be one row of data - it is simply a json string with dynamic content.
Now with datatables you can simply populate the table with aaData and aaCol by assigning a json string to it but my json string contains a column and data IE:
First_name:bob and so on.
A column - on Datatables would be populated with sTitle:Column1 etc and assigned to aaCol.
Does anyone know of a plug in that parses a json string into aaCol and aaData for use with datatables?
I believe you can solve your problem using this approach:
$(document).ready(function() {
$('#example').DataTable( {
"processing": true,
"serverSide": true,
"ajax": "scripts/objects.php",
"columns": [
{ "data": "first_name" },
{ "data": "last_name" },
{ "data": "position" },
{ "data": "office" },
{ "data": "start_date" },
{ "data": "salary" }
]
} );
} );
In the example above the dataTables uses a serverSide processing, the ajax return a object like this:
{
"draw": 1,
"recordsTotal": 57,
"recordsFiltered": 57,
"data": [
{
"first_name": "Airi",
"last_name": "Satou",
"position": "Accountant",
"office": "Tokyo",
"start_date": "28th Nov 08",
"salary": "$162,700"
}, ...
You can also set the column name using the "name" property inside the specification of each column.
You can the full example in the following link. If you need more assistance I can make a code on my own later today =)
You can check this JsFiddle to understand how to set the columns names
$user = $this->User->find( 'all' );
$this->set( 'users', $user );
I have this code in my controller.
In my view I have this.
echo json_encode( compact( 'users' ) );
It outputs json like this
{
"users": [{
"User": {
"user_id": "2",
"email": "email#test.com",
"name": "Blah"
}]
}
}
Is there anyway to format this to remove the entire array wrapped in "users", and also remove every object being a member of "User".
This makes it harder to use on the front end. I'd like it to look like this.
[{
"user_id": "2",
"email": "email#test.com",
"name": "Blah"
}]
Thanks for any help.
I don't fully understand what you mean by "remove the entire array wrapped in "users"" and "remove every object being a member of "User"", but according to your desired output format example, you'll need to extract and pass the exact data that you want to be encoded to json_encode, instead of passing everything using compact.
Extracting could be done with the Set or the Hash class (depending on your Cake version)
Assuming your model returns the data in the default CakePHP format, this for example:
json_encode(Set::extract('/User/.', $users));
should give you a structure like this:
[{
"user_id": "2",
"email": "email#test.com",
"name": "Blah"
}]
and with multiple users it should look like this
[{
"user_id": "1",
"email": "foo#test.com",
"name": "Bar"
},
{
"user_id": "2",
"email": "email#test.com",
"name": "Blah"
}]
Use like this:
$users= (Set::extract('/User/.', $users));
pr($users);
It will remove Model from result Array and then json_encode or whatever further usage.
More library functions Set class Here and Hash class Here
there!
I´ve one column in my jqGrid that is empty.
But i checked the object on chrome console and thats fine.
colModel definition
colModel:[
{name:'id',index:'id', width:55,editable:false,editoptions:{readonly:true,size:10},hidden:true},
{name:'firstName',index:'firstName', width:100,searchoptions: { sopt: ['eq', 'ne', 'cn']}},
{name:'lastName',index:'lastName', width:100,editable:true, editrules:{required:true}, editoptions:{size:10}},
{name:'books[0].nome',index:'books[0].nome', width:100,editable:true, editrules:{required:true}, editoptions:{size:10}},
{"formatter":"myfunction", formatoptions:{baseLinkUrl:'/demo/{firstName}|view-icon'}}
]
JSON response
{
"total": "10",
"page": "1",
"records": "3",
"rows": [
{
"id": 1,
"firstName": "John",
"lastName": "Smith",
"books": [{"nome": "HeadFirst"}]
},
{
"id": 2,
"firstName": "Jane",
"lastName": "Adams",
"books": [{"nome": "DalaiLama"}]
},
{
"id": 35,
"firstName": "Jeff",
"lastName": "Mayer",
"books": [{"nome": "Bobymarley"}]
}
]
}
chrome console inspect object
rowdata.books[0].nome
"HeadFirst"
Any one know where theres are possibles trick?
Tks!
You should use as the value of name property of colModel only the names which can be used as property name in JavaScript and as CSS id names. So the usage of name:'books[0].nome' is not good idea.
To solve your problem you can use jsonmap. For example you can use dotted name conversion:
{name: 'nome', jsonmap: 'books.0.nome', ...
In more complex cases you can use functions as the value of jsonmap. For example
{name: 'nome', jsonmap: function (item) {
return item.books[0].nome;
}, ...
You can find some more code examples about the usage of jsonmap in other old answers: here, here, here, here, here.
name is intended to be a unique name for the row, not a reference to a JSON object. From the jqGrid colModel options documentation:
Set the unique name in the grid for the column. This property is required. As well as other words used as property/event names, the reserved words (which cannot be used for names) include subgrid, cb and rn.
You can also observe how .name is used within grid.base.js - for example:
var nm = {},
...
nm = $t.p.colModel[i].name;
...
res[nm] = $.unformat.call($t,this,{rowId:ind.id, colModel:$t.p.colModel[i]},i);
Anyway, to get back to your question I think you will have better luck by passing down the book name directly - as strings and not objects - and referencing it by name as something like bookName.