I have a data format that I receive from jquery data tables editor Datatables Editor which looks like the one below and I need to parse it so that I can store it into db but I have not figured out a way of doing so.
{ action: 'edit',
'data[1][Name]': 'Some Text ',
'data[1][Rating]': '1',
'data[1][Division]': 'Some Text '
}
What is the best way to parse this form of data using javascript ? The editor library comes with a php library for parsing the data but I am using nodejs for the backend/
If you want to convert data[] into a literal, you could do something like this :
var prop, fieldName, literal = {};
for (prop in data) {
if (prop != 'action') {
fieldName = prop.match(/\[(.*?)\]/g)[1].replace(/\]|\[/g,'');
literal[fieldName] = data[prop];
}
}
→demo. It will produce a literal like
{Name: "Some Text ", Rating: "1", Division: "Some Text "}
that can be used to be inserted in a mongodb for example.
It simply loops through data, extracts each #2 [] and take the content of that bracket as property names to the literal. I do not at all claim this is the best method.
I have new and maybe a bit more systematic approach, that excludes risc of '[]' characters in regexed strings. Very simple way is to use custom ajax, I have used my own data:
const editor = new $.fn.dataTable.Editor({
ajax: (method, url, data, success, error) => {
$.ajax({
type: 'POST',
url: '/updateproductcode',
data: JSON.stringify(data),
success: (json) => {
success(json);
},
error: (xhr, error, thrown) => {
error(xhr, error, thrown);
}
});
},
table: '#mytable',
idSrc: 'productcode',
fields: ...
Then on serverside you receive object, whose key is your stringified data:
{'{"action":"edit","data":{"08588001339265":{"productcode":"08588001339265","name":"does_not_existasdfadsf","pdkname":"Prokain Penicilin G 1.5 Biotika ims.inj.s.10x1.5MU","suklcode":"0201964","pdkcode":"2895002"}
}:''}
If you parse the key of it with JSON.parse(Object.keys(req.body)[0]), you get your results:
{ action: 'edit',
data:
{ '08588001339265':
{ productcode: '08588001339265',
name: 'does_not_existasdfadsf',
pdkname: 'Prokain Penicilin G 1.5 Biotika ims.inj.s.10x1.5MU',
suklcode: '0201964',
pdkcode: '2895002' } } }
Related
I want to fill a jquery datatable by passing an array to it, the controller pass an array of users using ViewBag as following:
userInfo[] users = _context.userInfo.ToArray();
ViewBag.UsersArray = users;
In the view, I used ViewBag.UsersArray as a data source for the jquery datatable:
<script>
$(document).ready(function () {
$('#users').DataTable({
data: #ViewBag.UsersArray,
columns: [
{ data: 'id' },
{ data: 'username' },
{ data: 'balance' },
{ data: 'contract_id' }
]
});
});
</script>
I always got Unexpected token ']'
To use C# objects in script tags in Razor pages, you must first convert them to JSON. Razor does not do this automatically.
This way you can easily serialize your array to JSON:
<script>
$(document).ready(function () {
$('#users').DataTable({
data: #Json.Serialize(#ViewBag.UsersArray),
columns: [
{ data: 'id' },
{ data: 'username' },
{ data: 'balance' },
{ data: 'contract_id' }
]
});
});
</script>
The problem seems to just be that the array is being treated as a reference to an object rather than being enumerated. I would first try wrapping #ViewBag.UsersArray in quotes, and if that makes no difference I would "manually" enumerate through the array in your JS code and add each array element to the table's data property.
I have an endpoint which I call with Axios and the response looks like (for example):
items: [
{
url: "https://api.example1...",
expirationDate: "2019-11-15T00:00:00+01:00"
},
{
url: "https://api.example2...",
expirationDate: "2019-12-20T00:00:00+01:00"
},
{
url: "https://api.example3...",
expirationDate: "2020-01-17T00:00:00+01:00"
},
...and so on.
If I go to one of the url:s in the browser the structure of the JSON is:
fooBar: {
url: "https://api.foo...",
id: "123",
type: "INDEX",
source: "Foobar",
quotes: {
url: "https://api.bar..."
}
},
I need to get the quotes of the two first url:s in items:[] dynamically because they will disappear when the 'expirationDate' is older than today's date.
How can this be achieved? Thanks in advance!
If I understand the requirements correctly you need to:
get the list of items
get item details for first two items (to extract links to quotes)
get quotes for first two items
You can use promise chaining to execute these operations maintaining the order:
const getQuotes = (item) => axios.get(item.url)
.then(resp => axios.get(resp.data.fooBar.quotes.url));
axios.get('/items') // here should be the url that you use to get items array
.then(resp => resp.data.slice(0, 2).map(getQuotes))
.then(quotes => Promise.all(quotes))
.then(quotes => {
console.log(quotes);
});
Please find my proposal below. I gave two examples. You can get the whole quotes object, or just the URL inside the quotes object.
This is just a console log, but you can easily ie. append this data to a div in the html or pass this URL to some other function.
$(function() {
const address = 'https://api.example1...';
function loadQuotes() {
$.ajax({
url: address,
dataType: 'json',
}).done(function(response) {
response.forEach(el => {
console.log(`el.quotes`);
// or if you want to be more specific console.log(`el.quotes.url`);
});
});
}
loadQuotes();
});
If these are nested objects, just append fooBar.
For example change the .done part to:
.done(function(response) {
let qqq = response.quotes
quotes.forEach(el => {
console.log(`el.quotes`);
// or if you want to be more specific console.log(`el.quotes.url`);
});
Hi Guys I'm new to Django and Python... I'm using REST Framework to develop some webservices. I want to loop through all the orders of a JSON item. The request from javascript is done in this way:
function TestDjangoPostWithNoCsrlTokenAndWithMultipleObjectsJson() {
var JSONObject = new Object();
JSONObject.Orders = [];
JSONObject.Orders.push({ id: 1, Name: 'Name1', Description: 'Description1' });
JSONObject.Orders.push({ id: 2, Name: 'Name2', Description: 'Description1' });
JSONObject.Orders.push({ id: 3, Name: 'Name3', Description: 'Description1' });
console.log(JSON.stringify(JSONObject));
$.ajax
({
type: "POST",
url: URL_PostOrdersMultipleObjects,
headers: {
"Authorization": "Basic " + btoa("xxx" + ":" + "xxx")
},
data: JSONObject,
dataType: 'json',
success: function (data, status, xhr) {
console.log(JSON.stringify(data));
if (xhr.readyState == 4) {
if (xhr.status == 201) {
console.log("Created");
}
} else {
console.log("NoGood");
}
},
complete: function (xhr) {
},
error: function (xhr, ajaxOptions, thrownError) {
console.log(xhr.status);
console.log(thrownError);
}
});
}
On Django side, I have...
#api_view(['GET', 'POST'])
def JSONPostTest(request):
if request.method == 'POST':
stream = io.BytesIO(request.body)
obj = JSONParser().parse(stream)
for order in obj['Orders']: # First Example
serializer = QASerializer(data=order)
if serializer.is_valid():
serializer.save()
else :
return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST)
return Response('OK', status=status.HTTP_201_CREATED)
else:
return Response('OK', status=status.HTTP_201_CREATED)
If In javascript i stringify my object before to send it the above code works fine. The problems is when I don't stringify.
If I stringify
request.body =
b'{"Orders":[{"id":1,"Name":"Name1","Description":"Description1"},{"id":2,"Name":"Name2","Description":"Description2"},{"id":3,"Name":"Name3","Description":"Description3"}]}'
if I don't stringify
request.body
b'Orders%5B0%5D%5Bid%5D=1&Orders%5B0%5D%5BName%5D=Name1&Orders%5B0%5D%5BDescription%5D=Description1&Orders%5B1%5D%5Bid%5D=2&Orders%5B1%5D%5BName%5D=Name2&Orders%5B1%5D%5BDescription%5D=Description1&Orders%5B2%5D%5Bid%5D=3&Orders%5B2%5D%5BName%5D=Name3&Orders%5B2%5D%5BDescription%5D=Description1'
and
request.data
<QueryDict: {'Orders[1][Description]': ['Description1'], 'Orders[2][id]': ['3'], 'Orders[0][Name]': ['Name1'], 'Orders[0][Description]': ['Description1'], 'Orders[2][Description]': ['Description1'], 'Orders[1][id]': ['2'], 'Orders[0][id]': ['1'], 'Orders[1][Name]': ['Name2'], 'Orders[2][Name]': ['Name3']}>
I can stringify no problem on that. But I want to understand if it's possible to obtain the same result without stringifing starting from the QueryDict I have.
Thank you
You've not only constructed your JSON object in an unnecessarily verbose and complex way, you're also using the wrong data structure. If you want to iterate something, it should be an array (which maps to a list in Python), not an object (which maps to a dict). Your JS code should look like this:
JSONObject.Orders = [];
JSONObject.Orders.push({id: 1, Name: 'Name1', Description: 'Description1'});
JSONObject.Orders.push({id: 2, Name: 'Name2', Description: 'Description1'});
JSONObject.Orders.push({id: 3, Name: 'Name3', Description: 'Description1'});
(You could actually make that more compact by defining the objects inline with the array, but this is at least clearer for now.)
Now, it's simple to iterate in Python:
for obj in jsondata['Orders']:
...
Since you write you have a Serializer for Order I assume it is also a model on your backend and you would like to store it in the database. In that case I would not bother to manually deserialize the list of orders but let django-restframework unpack the nested child objects along with the parent.
Have a look here: https://stackoverflow.com/a/28246994/640916
I am getting the following exception when calling OData from my Kendo ListView:
"A binary operator with incompatible types was detected. Found operand
types 'Edm.Guid' and 'Edm.String' for operator kind 'Equal'"
DECODED FILTER:
$filter=OrganizationId eq '4c2c1c1e-1838-42ca-b730-399816de85f8'
ENCODED FILTER:
%24filter=OrganizationId+eq+%274c2c1c1e-1838-42ca-b730-399816de85f8%27
HAVE ALSO UNSUCESSFULLY TRIED THESE FILTERS:
$filter=OrganizationId eq guid'4c2c1c1e-1838-42ca-b730-399816de85f8'
$filter=OrganizationId eq cast('4c2c1c1e-1838-42ca-b730-399816de85f8', Edm.Guid)
MY WEB API CALL LOOKS LIKE:
// GET: odata/Sites
[HttpGet]
[EnableQuery]
public IHttpActionResult GetSites(ODataQueryOptions<Site> queryOptions)
{
IQueryable<Site> sites = null;
try
{
queryOptions.Validate(_validationSettings);
sites = _siteService.GetAll().OrderBy(x => x.SiteName);
if (sites == null)
return NotFound();
}
catch (ODataException ex)
{
TraceHandler.TraceError(ex);
return BadRequest(ex.Message);
}
return Ok(sites);
}
MY JAVASCRIPT KENDO DATASOURCE LOOKS LIKE:
var dataSource = new kendo.data.DataSource({
filter: { field: "OrganizationId", operator: "eq", value: that.settings.current.customer.id },
schema: {
data: function (data) {
return data.value;
},
total: function (data) {
return data.length;
}
},
serverFiltering: true,
serverPaging: true,
transport: {
parameterMap: function (options, type) {
var paramMap = kendo.data.transports.odata.parameterMap(options);
// Remove invalid Parameters that Web API doesn't support
delete paramMap.$inlinecount; // <-- remove inlinecount
delete paramMap.$format; // <-- remove format
delete paramMap.$callback; // <-- remove callback
// PLEASE NOTICE: That I have tried reformatting unsuccessfully
//paramMap.$filter = paramMap.$filter.replace("OrganizationId eq ", "OrganizationId eq guid");
//paramMap.$filter = "OrganizationId eq cast('81de6144-987c-4b6f-a9bd-355cb6597fc1', Edm.Guid)";
return paramMap;
},
read: {
url: buildRoute('odata/Sites')
, dataType: 'json'
}
},
type: 'odata'
});
If the OData service is of protocol version V4, the correct query URL should be:
$filter=OrganizationId eq 4c2c1c1e-1838-42ca-b730-399816de85f8
No single quotes is required.
I ran into this error querying OData 4.0 through Microsoft Dynamics. The other answers here didn't help unfortunately, even though they are exactly right. My issue was more with handing EntityReference's in filters.
I ended up having to adjust my filter to something like this, to target the foreign key properly. In the example below 'parentaccountid' is the foreign key in the entity I was querying. 'accountid' is the primary key in the accounts entity.
/opportunities?$select=opportunityid&$filter=parentaccountid/accountid eq 5e669180-be01-e711-8118-e0071b6af2a1
Every value which is having kind of an id to another entity reference in ms crm, should be evaluated like this.
$filter=_foodValue eq 593687F4-8B0C-E811-81B1-91CF10505DB5
Does not require quotes or guid string.
Please try
$filter=OrganizationId%20eq%20guid%27067e6162-3b6f-4ae2-a171-2470b63dff02%27
With PowerBi Rest API, I was able to fix the issue by putting the GUID within single quotes:
https://api.powerbi.com/v1.0/myorg/groups?%24filter=id%20eq%20'9c02ab25-0e94-4835-92e6-62ac6460acd0'
Im working with the parse javascript sdk and i want to add a key to an object in a Parse 'object' when saving it.
For ex:
var saveGif = new SaveGifTags();
saveGif.save({
type: req.body.type,
tag: req.body.tags[i],
gifObjects: newGif
}, {
success: function(data) {
console.log(data);
res.json(data);
},
error: function(data) {
console.log(data);
}
});
gifObjects is my object in the Parse Class. I tried to do something like this
gifObjects: gifOjects[gifObj.id] = newGif;
newGif of course is the object i want to save. This gave me an error of gifObjects is not defined. So i tried something like this
gifObjects[gifObj.id] : newGif;
that didnt work either. i want to create something like this:
{
hgs32: {
url: '',
image: ''
},
64522 : {
url: '',
image: ''
}
}
any suggestions?
Figured it out. Not sure what the downvote is for, but i had to create the object before i saved it.
var gifObjects = {};
gifObjects[gifObj.id] = newGif;
and then the save
saveGif.save({
type: req.body.type,
tag: req.body.tags[i],
gifObjects: gifObjects
},