Multi element JSON object from JavaScript - javascript

I have a Javascript JSON object
const student = { name: "bob", age: 7, grade: 6 }
and I can pass it to my Web API using axios POST command by
JSON.stringify(student)
and I can build my student object by looping an array and passing in a value such as
let studentArr= []
const student = { name: studentArr[i]["name"], age: studentArr[i]["age"], grade: studentArr[i]["grade"}
I'm using i in the example as the index because it could have 100 students. As long as I pass in only one value for i, everything works fine. My question is how can I make it into a multi-element JSON object from my array. I've been spoiled by Newtonsoft.Json where I can pull data from a SQL database and create a JSON object. If I just JSON.stringify(studentARR) is shows empty. I want to pass to the Web API all of the students on one post so the Web API can make a document and download it back.
I seen many different ways of trying to accomplish this and the methods seem to change over time. Thanks for the help

Why do you have to JSON.stringify if you are using axios. The declaration of axios.post accepts URL as first parameter and the data which is formdata or the JSON object as second parameter
I'm pretty sure that you might not need to use JSON.stringify if you are using axios to post to a Web API
Example of using Axios post method https://axios-http.com/docs/post_example

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

How can I create a Get request in Node.js to get specific object from json?

I am optimizing an api, therefore I need to use only data that is relevant for my analysis. I have created a route that pull out of the objects, but I just need 4 of them (account_manager, fronter, closer, management_fee and sales_date)
I am currently doing this:
you can use .find() with projection to retrieve only the relevant field
try this :
const model_CancellationKPI = await CancellationKPI.find({},{
account_manager:1,
fronter:1,
closer:1,
management_fee:1,
sales_date:1
}).sort({sales_date:-1})

Save/Load Variables in js

I'm trying to create a save/load function for my game in js, but I have basically no idea with how to go through with doing this. I can save variables to a JSON file or LocalStorage, but I don't know how to load them back into the program. I'm also pretty sure I'm exporting variables the wrong way as well. Any help?
Normally, I use JSON format to store and read data (of any type).
To save data (using key gamedata as example):
var myData = {
name: 'David',
score: 10
}
localStorage.setItem('gamedata', JSON.stringify(myData));
** without JSON.stringify, you data will be saved as string [Object object]
To retrieve the data back:
var savedData = localStorage.getItem('gamedata'); // savedData is string
var myData = JSON.parse(savedData); // parse JSON string to java object
setup a bin on www.myJSON.com. p5 has built in functionality for ajax requests such as loadJSON. that way it's not in local storage and you can access your data if you have it on github. I know your struggle, I used to deal with this sort of issue myself before I found myJSON

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!

Send javascript array object to ashx

I have an array of objects in javascript and I like to send this object to the server in a post request to ashx handler
I'm sending the information with this script:
var filtersArray = [{id:1, val:"filter1"}, {id:2, val:"filter2"}];
var object = {filters: filtersArray, id: 123, name: "object"};
$.post('handler.ashx', jQuery.param(object), function () {
//do some stuff
});
I can see in the chrome console the network params
Form Data
filters[0][id]:1
filters[0][val]:filter1
filters[1][id]:2
filters[1][val]:filter2
id:123
name:object
And in the handler I want to retrieve the parameter filter as an array, list or something.
I tried to do this: context.Request("filters[]") but the response is Nothing to retrieve the value I have to context.Request("filters[0][id]")
But this is not useful because the size of the list could be different in each request and with this solution I should have to add a parameter with the size and iterate parameters with this number.
Another option will be transfor to a JSON object and later deserialize the object in the server. But I prefer to not do that.
There is any other way to do this?

Categories

Resources