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.
Related
I'm working on a discord bot right now that reads responses off of a JSON file. The basic format is as follows:
"matt":
{
"insults" : ["test 1",
"test 2",
"test 3",
"test 4"
]
},
I'm currently working on a function that allows a user to use the !addInsult command, followed by a string, which will then append onto the existing array.
My desired workflow is as such:
User types in the following: !addInsult test 5. This would then modify the JSON object of insults under matt to the following:
"matt":
{
"insults" : ["test 1",
"test 2",
"test 3",
"test 4",
"test 5"
]
},
Doing this will allow me to let my friends add data to my bot without needing me to manually edit the JSON every time we want something new.
What would the best way of going about this be? I've looked into this thing called push, but I don't really understand how that works.
This is what I have so far. I think I'm going in the right direction, but I'm not sure:
The following is established at the beginning of the script:
// contains the insults
var insults = require('./insults.json');
// get the insults from the json file specific to user
var insultsString = JSON.stringify(insults);
var json = JSON.parse(insultsString);
And here is the function that will be doing appending:
// command that allows users to add to the pool of insults
function addInsultCommand(args, receivedMessage)
{
// create an object that contains the information for the json file
json["bot"].push(["test"]);
receivedMessage.channel.send(json.matt.insults[0]);
}
so there is a misconception here; JS does not write to files.
You're using webpack, which let's you require the .json using a webpack loader, but this will ONLY work when using the dev server. This will not work when distributing your code, because the .json will will be encoded into your output bundle.
.js can not write a file for you ( except locally ), so what you need to do is two fold:
1) Download the .json from the webserver, without using a webpack loader.
2) modify the JSON data in memory
3) upload the JSON data to the web server for it to write the file for you.
In addition to this, I can not follow your example code. you reference receivedMessage.channel.send, but I do not see where this is defined. Is this some kind of discord integration? You may need to re-state your question along with a minimal proof of the issue with reproducible test code.
JSON.stringify will turn a javascript object into a JSON object. JSON.parse will do the opposite(turn a JSON object into a Javascript object). Assuming insults.json is a json object, you do not need to convert it into a string. You can just do JSON.parse(insults) to convert it into a javascript object.
I am not sure what you were intending to do with the args variable in addInsultCommand but I am going to ignore for now and give you some steps to follow below.
1) Turn JSON object(insults) into JS object
2) create a function that takes a JS object and a receivedMessage(the insult to add) and assigns it to the correct place in the JS object.
3) convert the JS object into JSON(using JSON.stringify) and replace the contents of insults.json with the the updated value.
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>
I'm doing a Three.js development. specifically I am creating meses in THREE.JS but as charge thousands of vertices, takes a long time in the figures created. So my idea is to save the object that is created in .json format so that when you run the application simply need to load the .json and so do not delay.
I tried using the library: DEBUGOUT
but the json is so great that the browser crashes (I think).
I have also tried to:
JSON.stringify ()
to make a copy and paste, but I get an error as cyclic structure something.
from google chrome I tried to save as a temporary variable but do:
copy (temp1);
I get [object Object] What I can do?
this is my json:
http://i.imgur.com/Db4feaP.png
I need sabe my .json in a file..
thank you!
I think you will be very happy if you try out Firebase, which will store and retrieve your json object trivially.
Here is an example where they store the pixels of a canvas object in firebase : https://www.firebase.com/tutorial/#session/x0mesao7io1
code looks basically like this:
var ref = new Firebase("https://docs-examples.firebaseio.com/web/saving-data/fireblog");
var usersRef = ref.child("users");
usersRef.set({
alanisawesome: {
date_of_birth: "June 23, 1912",
full_name: "Alan Turing"
},
gracehop: {
date_of_birth: "December 9, 1906",
full_name: "Grace Hopper"
}
});
Also you'll be happy to know that Firebase will work even if you're offline, then it will sync when online.
UPDATED:
If the object you are trying to save cannot be converted to json, then what you need to do is separate the main data from the object, and store that. So to reload your data, you will recreate the basic structure of the object in javascript, then insert the data into the object.
It's hard to tell where the vertices are stored in your object from the image, but it seems like what you may want to do is actually extract just the vertices data and save that, or something similar.
UPDATE2:
It seems threejs may have a .toJSON() function that you need to use to extract it as a json object: https://github.com/josdirksen/learning-threejs/blob/master/chapter-08/03-load-save-json-object.html this example shows converting the threejs object to a json, and storing, loading the json, then recreating the threejs object.
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!
I am trying to create some JSON to be used for displaying a chart using Highcharts
http://www.highcharts.com/
I have copied one of their examples:
http://www.highcharts.com/stock/demo/basic-line
Click "View Options" under the graph to see the source. There is also a JSFiddle there to play with
If I copy that locally it all works fine.
The problem is when I try to use my own data source.
I have an ASP.Net MVC controler which is spitting out a list of arrays, just like their data source. However, that doesn't work.
Their datasource looks like this
http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?
and they retrieve it like this
$.getJSON('http://www.highcharts.com/samples/data/jsonp.php?filename=aapl-c.json&callback=?', function (data) {
So I thought I'd take a step back and copy thier data exactly and put it in a text file on my server and try that:
So I tried this
$.getJSON('/data.txt', function (data) {
and this
$.get('/data.txt', function (data) {
but neither work
I have also tried using both JSON.parse and jQuery.parseJSON after retrieving the data, but again - that doesn't seem to work
I am also wondering what the ? is at the start of their data
Their data looks like this
?([[<some data>],[some data]]);
I don't get any error message, the graph just doesn't display
any ideas?
SOLVED IT
Just need to retrive the data and turn it into an array and pass it to the chart.
Needs to be an array, not JSON
That datasource is ouputting JSONP, which is for cross-domain AJAX requests. It's not valid 'raw' JSON because of that extra callback(...) wrapper.
Read up about it here: http://api.jquery.com/jQuery.ajax/ under the 'dataType' section.
As you say in your tags, it's not JSON, it's JSONP. Do not parse it, catch it with a callback. Use jQuery.getScript to do it, and define function callback(data). Inside that function, data should contain the (parsed) object. Also, replace the ? in the URL with callback (or whatever you named your function) - ? is not a valid identifier in JavaScript, so ?([....]) is nonsense.