Create json object with javascript - javascript

I've tested my REST service with success using Advanced Rest Client, where I'm sending a payload that looks like this:
{
"comments":"test comments",
"internal_verification_areas":[
{
"area_id":"1",
"selected":"1",
"notes":"notes1",
"status":"1"
},
{
"area_id":"2",
"selected":"0",
"notes":"notes2",
"status":"0"
}]
}
As mentioned my REST function executes with success.
I then moved to implement the whole thing on my web-interface and created the internal_verification_areas object as follows:
var verification_areas = {
internal_verification_areas: [
{
area_id:"1", // no need to quote variable names
selected:"1",
notes:"noter",
status:"1"
},
{
area_id:"2", // no need to quote variable names
selected:"1",
notes:"noter2",
status:"1"
}
]
};
The whole thing is then fed into my request like this (comments parameter is fetched from a textarea):
$.post("createInternalVerification.php",{comments: $('textarea#korrigeringer').val(),internal_verification_areas: verification_areas}
createInternalVerification.php will json encode the data and request the service.
The problem is, that i get an error saying: "Integrity constraint violation: 1048 Column 'area_id' cannot be null". I assume there is something wrong with my posted data, but i can't figure out what. From my POV my Advanced Rest Client payload looks similar to the payload i send from my web-interface.
EDIT:
I've noticed that the network tab (google chrome) shows some differences in my payload. I'm returning internal_verification_areas in my response to analyze the difference.
(MY WEB INTERFACE RECEIVES)
{"error":false,"message":"Intern efterprovning oprettet","test":{"internal_verification_areas":[{"area_id":"1","selected":"1","notes":"noter","status":"1"},{"area_id":"2","selected":"1","notes":"noter2","status":"1"},{"area_id":"3","selected":"1","notes":"noter3","status":"1"}]}}
(ADVANCED REST CLIENT RECEIVES)
{"error":false,"message":"Intern efterprovning oprettet","test":[{"area_id":"1","selected":"1","notes":"jAAAAAAA","status":"1","id":"4"},{"area_id":"2","selected":"0","notes":"NEEEEEJ","status":"0","id":"5"}]}

Guess I messed up my understanding of objects and arrays. Turns out my web-interface was sending and array with and object with arrays. Changing it (as shown after this post) fixed my mistake. I'm so sorry zerkms for wasting your precious time and causing an immense annoyance to your unicum skilled mind. I find it more and more frightening to post questions on StackOverflow with the presence of such skilled and godlike figures who constantly remind minions such as myself that Stackoverflow has become the very bedrock of arrogant developers.
var internal_verification_areas = [
{
area_id:"1", // no need to quote variable names
selected:"1",
notes:"noter",
status:"1"
},
{
area_id:"2", // no need to quote variable names
selected:"1",
notes:"noter2",
status:"1"
},
{
area_id:"3", // no need to quote variable names
selected:"1",
notes:"noter3",
status:"1"
}
];

Related

I have some raw JSON stored in a variable and just want to post it to an API

I have been traversing through Stackoverflow and everywhere else on the web to try and find a solution to my issue..
I am working in Javascript and attempting to POST a small section of JSON to an endpoint in the API i know is working (I have completes the GET and POST manually in Postman)
Here is my issue..
I want dont really want to do the "GET" in my programme I just want to either reference the file or even just store it in a little variable.
So for example I have in my code:
var OauthUpload = {
"objects": [
{
"name": "api",
"serviceID": 16,
"properties": {}
}
],
"version": "integration",
"environment": "redshift"
}
Then I am trying to reference this in the JS function:
function ApiPostOauth (port) {
$.post(OauthUpload, "http://docker.dc.test.com:" + getActualPort(port) + "/rest/v1/oauth/import", runner);
}
But I am having no joy! I have seen a few different silutions but none seem to fit for me.
Basically I want a way to just:
Reference my own JSON as a variable and then insert tht so my function "ApiPostOauth" has that inserted before it runs?
Thanks guys
Steve
I have put together an example for your use. When executing this code, the server will return the same object it is sent. So the 'OauthUpload` object is sent as the request body and the server returns the exact same object. Note: if you don't see output in the output panel when running the sample I will need to restart the server (leave a comment). This is here to demonstrate:
[EDIT] - after re-reading your question, it appears you would like to pass the 'OauthUpload` object into the function. I've updated the example.
You have a mistake in your call to jQuery post() method. As shown in the comments, the first two arguments are reversed in the call to post().
Since you didn't pick up on that, I decided to provide an example using your code. Since I don't have your server, I stood up a server for this example. So the URL and port will be different, but the AJAX call will be the same.
Please pay close attention to the OauthUpload object. Notice the property names are no longer surrounded by ". I removed these quotes because they seemed to be causing you confusion about JavaScript objects and JSON strings (there is no such thing as a JSON Object regardless of what you read on the web - JSON is a string format).
Next, look at the differences between the call made to $.post() in my example and your code. You will see the URL comes first in that call.
let url = "//SimpleCORSEnabledServer--randycasburn.repl.co/rest/v1/oauth/import";
let OauthUpload = {
objects: [{
name: "api",
serviceID: 16,
properties: {}
}],
version: "integration",
environment: "redshift"
}
ApiPostOauth(OauthUpload);
function ApiPostOauth(data) {
$.post(url, data, runner)
}
function runner(data) {
document.querySelector('pre').textContent = JSON.stringify(data, null, 2);
}
<pre></pre>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

Configuring the data of the AjaxAppender Request Log4Javascript

I am very new to Log4Javascript and logging in general, so bear with me.
I am attempting to POST the logs to a CouchDB. I am receiving an error from the server:
{"error":"bad_request","reason":"Document must be a JSON object"}
Okay cool. So its not a JSON Object, I can fix that.
Except that I can't figure out how.
The code I am using is:
var log = log4javascript.getLogger();
var ajaxAppender = new log4javascript.AjaxAppender(url);
var layout = new log4javascript.JsonLayout(true, false);
ajaxAppender.addHeader("Content-Type", "application/json");
ajaxAppender.setLayout(layout);
log.addAppender(ajaxAppender);
// Test the logger
log.debug(JSON.stringify("Hello world!"));
Everywhere I have searched says this is the way to send it as a JSON object, so I imagine this is correct.
When I look at the request payload, I realize that the CouchDB server must not like the way it is formatted, which is like so:
[
{
"logger": "[anonymous]",
"timestamp": 1487961971605,
"level": "DEBUG",
"url": "url.to.couchdb",
"message": "\"Hello world!\""
}
]
As you can see, it is a JSON object within an array, and I believe this is where my problem lies.
So my questions are:
Did I miss something in setting up the AjaxAppender and the JsonLayout?
Is there a way to change the format of the Request Payload with log4javascript?
If not, is there a way in CouchDB that when a document is POSTed, I can intercept and change the Request Payload and continue on, so it removes the array (that I am assuming it does not like)?
Thanks.
I have found my answer.
The JsonLayout has properties called batchHeader and batchFooter among others, but these two were the culprits for me.
For whatever reason, it still included them even though I was not doing batch log sending, so I removed both of them like so:
...
var layout = new log4javascript.JsonLayout(true, false);
layout.batchHeader = "";
layout.batchFooter = "";
...
This fixed my problem and I successfully POSTed logs to CouchDB.
Hope this helps someone else.

Storing entire JSON object in PostgreSQL DB

I'm sending a JS object from my front-end to my Java backend, and I'm passing a object like so, which contains different types
wrapperObject = {
JSONOBJ = {
'key': 'value'
},
id: '123',
date: 'exampledate'
}
My java backend then takes this wrapperObject and converts every field inside into a value inside of a hashmap Map. Whenever it reaches the JSONObject, however, it parses it and attempts to insert into the db and I reach a
bad SQL grammar []; nested exception is org.postgresql.util.PSQLException: No hstore extension installed.
What can I do about this, and is there a better way of approaching this?
It sounds like it may be as simple as adding the hstore extension. The PostgreSQL documentation for installation looks pretty straightforward:
Let me know if I'm missing something, hope this helps!

Issue with JSON.parse , don't know why is not parsing everything

I'm developing a web app with Node.js using Sails framework(based on Express) and i'm using a third party image solution called Transloadit (no need to know Transloadit).
Anyway, that's not the problem, i'm been able to implement the Transloadit form and receive the information from their API.
My problem is that, Transloadit gives me the response as a String, and I need to access the response objects, so i'm using var objRes = JSON.parse(req.body.transloadit); to parse it to an JSON object, and when I console.log(objRes); the object is not correctly parsed, i get this: (see all JSON here https://gist.github.com/kevinblanco/9631085 )
{
a bunch of fields here .....
last_seq: 2,
results: {
thumb: [
[
Object
]
]
}
}
And I need the data from the thumb array, my question is, Why is doing that when parsing ?
Here's the entire request req.body object: https://gist.github.com/kevinblanco/9628156 as you can see the transloadit field is a string, and I need the data from some of their fields.
Thanks in advance.
There is nothing wrong with the parsing of the JSON -- in fact there is no problem at all.
consol.log limits the depth of what it is printing which is why you are seeing [object] in the output.
If you want to see the full output in node.js then just use the inspect utility like this;
console.log(util.inspect( yourobject, {depth:null} ));
and that will print the entire content.
Note that this is just an artifact of console.log printing it.

JSON spreadsheet returns null, or am I an idiot

So, have been trying to get a javascript to read a spreadsheet, but needed it private rather than public, so spent quite a bit of time trying to figure out how to do that. It is actually quite easy, or seems like it is, except that I still can't read the spreadsheet. Will cover private spreadsheets through the cloud console in the end.
So, I have a rather simple spreadsheet which contains about 6 columns, (including customer emails and similar, hence why private). And I have been playing about trying to get it to work for the last couple of days.
First, the string!
So to enable this I first need a string that will return a json object (is that what I am expecting back?)
https address: https://spreadsheets.google.com/feeds/list/
Sheet ID :
Additional : /od6/private/full
Command : ?alt=json-in-script&callback=importGSS
or full string : https://spreadsheets.google.com/feeds/list//od6/private/full?alt=json-in-script&callback=importGSS
This seems to work quite fine, if I remove the json part it shows me the data sheet, if I ad it, I get an empty file instead.
So now to the code.
The function that SHOULD be returning the object is the following (spLink) contains the link above.
function loadData(spLink){
$.getJSON(spLink).always(function(data) {
console.log("Object created!");
console.log(data);
}).fail(function(message) {
console.error('Something went pretty wrong!');
console.error(message);
}).done(function(){
console.log('Done!');
});
}
The only thing I can really tell about it is that data continues returning null, and I can't really figure out where else the data may end up.
Have tried both with and without callback.
The list feed only works if there are no empty cells in a row with data, among other pitfalls.
Use the cell feed instead, which requires more code because you wont get the data organized by rows.

Categories