How to interpret extended json data - javascript

Description of the problem
I will not write any codes as much of my problem is something linked with the knowledge to interpret some data. I am doing a project and had to use a nonsql database to store data the sampled information from a microcontroller. The chosen db was mondodb. I wrote all the code that stores the info and now i want to exhibit the date on a html page. The problem is that when i do the request using restapi to the mongodb, the json that was stored there comes in the extened json format, i.e.:
"_id": {
"$oid": "6230d05dcf81542c5aabc30b"
},
"sensor": {
"$numberDouble": "1"
}
But it should have come as the data is stored in the db:
"{
_id": "6230d05dcf81542c5aabc30b",
"sensor": 1.0
}
As you can see, the the json comes with extra information linked to the type of the variable that is stored. But i don't really know how to use that information in javascript. I would just read it for example as json.sensor.$numberDouble if i wanted to get the information about the sensor instead of json.sensor if the json was in the normal way. I don't see much of an use to the extended version. Is something i am doing wrong?

Make sure, that you Parse API response, like-
response.json()

It looks like you're getting back an EJSON response. If you want to send back standard JSON response then that should be set as the Content-Type on the server response.
function(req, res) {
data = { ... }; // Your data here
res.setHeader("Content-Type", "application/json");
res.setBody(JSON.stringify(data));
}
If you don't have control over the server side, then convert the EJSON back to plain JSON using the meteor EJSON library.

Related

How to send an object in postman

I was trying to make a post request to the api route I just created.
In the backend I have something like this
console.log(typeof req.body)
console.log(req.body)
const { firstName, lastName, email, phoneNumber } = req.body
console.log(`Variable Values`, firstName, lastName, email, phoneNumber)
Here I am getting typeof as String and body as this
{
firstName: "Varun",
lastName: "Bindal",
email: "iva#gmail.com",
phoneNumber: "+91-8888"
}
What I want is that the typeof to be object so I can de-structure it, How can I make a request from postman in this case (I don't want use JSON.parse)
Click the "Text" beside it will show you a dropdown. Just choose "JSON" instead of "Text"
Choose the JSON option as shown in the picture.
You should change the type of body from raw text to JSON (application/json) by clicking on the text button right next to your GraphQL option.
Your object body is of type text. Change it to JSON using the little dropdown and the POST request will work.
Cheers!
Why don't you want to use JSON.parse?
It's important to know that JSON and a javascript object are two different things.
JSON is a data format format that can be used in various environments while a javascript object is a data structure/concept in javascript.
When making a HTTP request you can send data via a few different methods. A few prominent ones being XML, Binary and JSON (They all will be represented as text, even binary).
Since you're building a API with javascript I would recommended that you use JSON in your requests and responses. JSON has also somewhat become the "standard" for APIs these days. It's also very easy to parse JSON to javascript objects and the other way around.
Please note that you maybe also need to tell postman to set the Content Type Header to application/json. You also would need to change your body to be actual valid JSON:
{
"firstName": "Varun",
"lastName": "Bindal",
"email": "iva#gmail.com",
"phoneNumber": "+91-8888"
}
I can recommend that you read the following article explaining what JSON is and how you use it: https://www.w3schools.com/js/js_json_intro.asp

Is it risky to parse JSON string from websockets?

I'm writing an Angular2 web application, and I want bidirectional communication with the server, so the perfect solution is with websockets.
Mozilla fundation teaches to use JSON.stringify(msg) to parse a string that represents a JSON message, both for sending and receiving data with websocket. This leads to some thoughts on injection. For example, suppose the following JSON document being transfered from the server to the client's machine:
{
message{
from: "paul",
text:"hello!",
date:"01/01/2017"
}
}
Now suppose paul changes his name to "paul\" and sends the following text:
,text: alert('xss'),something:"
then the following JSON received by the client would be:
{
message{
from: "paul\",
text:",text: alert('xss'),something:"",
date:"01/01/2017"
}
}
which is, in fact, the following JSON (just rearranged):
{
message{
from: "paul\",text:",
text: alert('xss'),
something:"",
date:"01/01/2017"
}
}
which could cause problems, depending on what is done with this JSON, I guess. Is there some way to prevent these things, or is the JSON.stringfy technique safe because when inserting data from the JSON into the DOM, the text attribute would be undefined because alert('xss') is not a string (or does not return anything)?
Also, see that if there's no problem with calling a function like alert(), we were able to set the something variable to anything we wanted, this is for sure risky.

Accessing JSON data when response contains both JSON data and text

Initially the content from the server was JSON data.And I was able to access the data perfectly.
{ "status":"ok", "artifact":"weblayer-war", "version":"0.0.41-test-data", "buildtime":"test-data" }
Now the response from the server has been changed to json data + text data.
{ "status":"ok", "artifact":"weblayer-war", "version":"0.0.41-test-data", "buildtime":"test-data" }
Properties for service:
=======================
ServiceEndpoint: https://somedomain:1200/web/Servlet/SOAP/Services
Certificates: false
DocumentName: note.pdf
So whether changing the content-type to application-text and using split method is the only way we can solve this or Is there any better approach?
As mentioned in the comments, mixing JSON and pure text data is wrong (as it defeats the advantage of using standardized data format) and should be avoided. Maybe that is some kind of debug log that was accidentally included in the production code?
If not, you should read just the first line of response and parse it as JSON data, ignoring the rest, hoping for no more changes in response structure ;)
You really should overthink your API design.
What about adding the text part as part of your JSON?
{
... // your JSON properties here
"serviceProperties": { // properties for service
"ServiceEndpoint": "https://somedomain:1200/web/Servlet/SOAP/Services",
"Certificates": false,
"DocumentName": "note.pdf"
}
}

Converting PHP object to JSON object using only Javascript

I am making a mobile app with Phonegap and using Wordpress as a backend. I am using Advanced Custom Fields with a Google Maps post field which returns a PHP object to the app using JSON API. My Wordpress backend sends a normal JSON object to the app, but inside that object is where a stringified PHP object is returned.
I need to convert the PHP object to a JSON object somehow on the client side(the app which is not in Wordpress). I have looked at other answers that say to use json_encode for this but my problem is that the app is just HTML/Javascript and no PHP. Is there a way to use PHP code in the middle of a Javascript function to do this? Or would it be better to change the backend so that it returns a JSON object instead of a PHP object in the first place? If so, how do I do that?
My experience in PHP is still somewhat limited so any help is appreciated.
edit: To clarify a bit more, I am using Wordpress on a separate domain from my Phonegap app and only using the JSON API plugin on the Wordpress end. I am then using jQuery Ajax calls to retrieve data from the Wordpress backend.
Also the returned PHP object looks like this: a:3:{s:7:\"address\";s:48:\"8915 W 159th St, Orland Hills, IL, United States\";s:3:\"lat\";s:17:\"41.60111599999999\";s:3:\"lng\";s:11:\"-87.8364575\";}
Another way I just thought of as well, would it be possible to just leave it as a PHP object and still read out the values from it somehow? I don't NEED it to be a JSON array, I just need a way to read the individual elements in the array in one way or another.
Here is also a tiny snippet of the JSON returned to clarify what I'm talking about.
"custom_fields": {
"location": [
"a:3:{s:7:\"address\";s:48:\"8915 W 159th St, Orland Hills, IL, United States\";s:3:\"lat\";s:17:\"41.60111599999999\";s:3:\"lng\";s:11:\"-87.8364575\";}"
]
}
That of course isn't the entire JSON object but it gives you an idea of what I'm dealing with.
I know you have a solution that works on the front end, but I still think it'd be better to fix this on the server.
Based on our conversation in the comments, I've had a closer look the code in the WordPress forum. The problem seems to be that the location field is an array of strings, not just a string. maybe_unserialize (and is_serialized, which it uses) don't handle arrays. Here's the updated code, which you should be able to drop into your theme's functions.php. I did a quick test, and it works for me.
class unserialize_php_arrays_before_sending_json {
function __construct() {
add_action( 'json_api_import_wp_post',
array( $this, 'json_api_import_wp_post' ),
10,
2 );
}
function json_api_import_wp_post( $JSON_API_Post, $wp_post ) {
foreach ( $JSON_API_Post->custom_fields as $key => $custom_field ) {
if (is_array($custom_field)) {
$unserialized_array = array();
foreach($custom_field as $field_key => $field_value) {
$unserialized_array[$field_key] = maybe_unserialize( $field_value );
}
$JSON_API_Post->custom_fields->$key = $unserialized_array;
}
else {
$JSON_API_Post->custom_fields->$key = maybe_unserialize( $custom_field );
}
}
}
}
new unserialize_php_arrays_before_sending_json();
If you're using a JSON API to retrieve the data, then why don't you deliver the data in JSON format to your app? Otherwise you seem to remove much of the point of using an API in the first place... You could of course parse that string in JavaScript if you really want to but that's a very ugly and error prone solution.
The JSON API plugin does seem to use JSON:
https://wordpress.org/plugins/json-api/screenshots/
I need to convert the PHP object to a JSON object somehow on the client side(the app which is not in Wordpress).
This bit here leaves me confused. You do not have PHP objects on the client-side, PHP is a back-end technology. What is returned to the client is a string which can be HTML, XML, JSON, plaintext on any other form of encoding.
That said, saying you have an object $obj in PHP, you could pass it to your front-end application creating an end-point retrieve_object.php and in there:
echo json_encode($obj);
So long as that is the only thing your are outputting, you lient-side app can make a request (Eg: AJAX) to retrieve_object.php and get the json object.
BUT , and this is important (!) in doing so you serialize object properties. You will lose any PHP object method. If any object property is an object itself (EG: A DB Connection) then this will be lost too.
Hope this helps!

process csv/json data in java servlets and javascript

I need an opinion on how to approach my problem. I have no idea on how to start and on how to implement which functions on which parts of the software. So this is what I want to do:
I have a Java servlet which creates a simple csv file:
name1, value1
name2, value2
etc.
This needs to be somehow converted to JSON data, so it can be displayed on a jsp page:
[
{
"name": "name1",
"value": "value1"
},
{
"name": "name2",
"value": "value2"
}
]
Then the user will be redirected to the jsp page. Is it possible to send the whole JSON structure via request object to the jsp page? Or is it the easiest if all processing is done in javascript and only the path to the csv file is sent via request object?
I'm kind of lost on this, since I first started last week with programming of web applications. I'd just need a push in the right direction and then I should be able to figure out the rest on my own ;)
First, look for a CSV parser which can turn a CSV file into a List<Bean> or List<Map<K,V>>.
Then, look for a JSON parser which can turn a List<Bean> or List<Map<K,V>> into a JSON string.
Finally, just do the math and set the resulting JSON string as a request attribute which you print in JSP as if it's a JS variable, like so <script>var data = ${data};</script>.

Categories

Resources