How to update json file in AngularJS - json

I want to update the existing json file in AngularJS
JSON file:
{
"text1": "Click here to edit!",
"text2": "Click here to edit!",
"text3": "Click here to edit!",
"text4": "Click here to edit!"
}
I want to update this JSON file as:
text1: "Abc"
and save this changes in JSON file

You can not update a json file without using a server-side language like PHP or python. Basically it is security compliance. For more understanding kindly go through
https://docs.angularjs.org/guide/security
https://docs.angularjs.org/api/ng/directive/ngCsp
and
https://developer.mozilla.org/en-US/docs/Web/Security/CSP

Imagine you have getjson.php and savejson.php in the server which work exactly as their names suggest.
Now use $http service of Angular to retrieve your json from the server.
$http.get("getjson.php").then(function(response){
$scope.myJsonObject = response.data;
//Your json becomes JS object here. Change it the way you want
$scope.myJsonObject.text1 = "Abc";
});
Use $http service again to send your json back to the server.
$http({
method: "post",
url: "savejson.php",
data: $scope.myJsonObject,
headers: { 'Content-Type': 'application/json; charset=utf-8' }
});
This is the basic. Please note that you need to do your php part to save/load your json file. Also you should handle errors of the $http service.
Please see how $http service and promises work.

Related

How to: (a) send JSON data from the browser to the controller; and (b) send the transformed data to SQL Server within ASP.NET MVC?

I have a form which includes a variety of <input> elements and makes use of 1-to-n tabulator tables for data input. I have managed to successfully assemble data from these elements into a JSON string. I am now attempting to complete the following two steps:
Using Ajax, post the JSON object to my web server; and
In the ASP.NET MVC controller, upload the deserialized JSON data into a SQL Server 2016 table.
My client-side script to POST the JSON object is as follows:
var myJson = "the data from the form elements is programmatically inserted into the JSON string";
// use parseJSON() to test the syntax
try {
var obj = jQuery.parseJSON(myJson);
}
catch(error) {
console.log(error);
}
$.ajax({
type: "POST",
url: "/Dailies/UploadJson/",
dataType: 'json',
data: JSON.stringify(myJson),
contentType: 'application/json',
crossDomain: true,
cache: false,
success: function(data) { console.log(data); }
});
The method called within my ASP.NET MVC controller appears as follows:
[HttpPost]
public IActionResult UploadJson(Object jsonFile)
{
// insert data into SQL Server table
}
Note: I have already created the appropriate domain model within my ASP.NET MVC app and have also added a DbSet reference to the DbContext model. I have verified my ability to insert rows into the SQL Server table using mock data.
When I place a breakpoint inside the UploadJson() method, I find that the jsonFile object is null.
My quandry at this point is two-fold:
I can't seem to get JSON data from the client to the web server; and
I need to better understand how to transform the JSON data (once received) for upload into my database.
Any assistance is greatly appreciated.
Although there are plenty of questions related to this, the answers to those typically refer to binding to a model instead of just the json string. But those will also help you.
It looks like there are two things:
I would change the controller to receive a string instead of an object.
You'll need to update the json data you're passing to the controller to match the parameter name of the controller. So in this case, the controller would receive a parameter named jsonFile. So in the $.ajax method you'll want update the data to something like:
data: { jsonFile: JSON.stringify(myJson) }
UPDATE:
remove the Content-Type of application/json

How to parse JSON object at server side?

I am trying to send data to a server (local rest API) from react using post request, if i send an object like this:
{key:"value"}
then i get this at the server:
{ '{"key":"value"}': '' }
It's converting the whole object into key-value pair.
How can i solve this issue?
axios.post('http://localhost:5000/animals', JSON.stringify(data))
.then((response)=>{
console.log(response);
});
If I don't stringify, then I get an empty object at the server, but if I do stringify, then I get this sort of object as mentioned above. Is there any way to convert it back to a normal object?
It looks like the server expects to get data in application/x-www-form-urlencoded encoding, not application/json.
Why?
application/x-www-form-urlencoded encoded data looks like
key1=value1&key2=value2&....
But values are optional, so
key1&key2=value2
works too.
You are sending {"key":"value"} which to the server looks like a key without a value. Since it looks like you have control over the server, change the server implementation to parse the request body as JSON instead. How to do that depends on the framework you are using on the server.
If you are using express.js, use bodyParser.json(). Alternatively send the data application/x-www-form-urlencoded encoded, not as JSON, as suggested by Chinedu.
Performing a POST request with axios
axios.post('/user', {
firstName: 'Fred',
lastName: 'Flintstone'
})
.then(function (response) {
console.log(response);
})
.catch(function (error) {
console.log(error);
});
Can you try constructing the data you want to send as the above exam, send to your api and see if the dummy data comes. No json parse or stringfy needed.
Are you using body-parser middleware in your nodejs express app?

Scraping - catch json response with python

I need to scrape a website with a "load more" button.
I need to catch the json response (which is invisible in the html code) and parse it to build URLs
This is the JSON post request response
I'm using Selenium, python.
how do I ?
tHX
You can bypass actually clicking on the "load more" button by reading the API call that the website is sending when you click the button and then sending it via Selenium. If you send it through Selenium, you can capture the response. Here's what I've been using an Angular website. You'll have to modify it to work with the website you're using, but this should get you started.
call = """
$http = angular.element(document.body).injector().get('$http');
var done = arguments[0];
$http({
method: 'POST',
headers: {
"Content-Type": "application/json"
},
data: {
foo: "bar"
},
url: "https://request.url/"
}).then(data => done(data));
"""
json_response = driver.execute_async_script(call)
The execute_async_script method will make the call and wait for a JSON response.
You can also right-click on the xhr in Chrome DevTools and copy the API call, which should make it easier to recreate it with selenium.
Let me know if you have follow-up questions.

ReactJS: Unable to send JSON data and PDF file in one POST call

I am working on GRAILS-ReactJs based project which involves a scenario where I need to send the RESUME and the JSON data in one POST call.
However, I am able to send file in one call but the data I am getting is null.
I am using Grails-3 at my server side and receiving the POST request as multipart file. I want both JSON and Multipart file object to be combined in one object to send to the server and want to receive the file and the JSON data both at the server side.
I have tried changing the content type of the header but ut doesn't work.
You can't post JSON data along with the file or any other attachment. You can post it as form data to your back end. The form data is passed as a multi-part data to the server with relevant boundaries. Here's a sample code for your reference. You may pass json data along with the formData as key, value pairs.
export function postAttachment (fileData, fileName) {
let formData = new FormData()
formData.append('prop1', 'value1')
formData.append('prop2', 'value2')
formData.append('upload', fileData, fileName)
return fetch('/your/endpoint', {
headers: {
'Accept': 'application/json',
'header1': 'headerValue1'
},
method: 'POST',
body: formData
})
}
Hope this helps. Happy Coding !

How to get indented JSON output in asp.net MVC 5 to view in browser?

This is only for debugging purpose. Only returning JSON, outputs unreadable JSON string on webpage. Is there any quick solution to view formatted json on webpage?
Looking for a C# function that will take json object and return formatted output as string from my action method.
Just change JSON global settings in your Global.asax file.
GlobalConfiguration.Configuration.Formatters.JsonFormatter.SerializerSettings = new JsonSerializerSettings
{
Formatting = Formatting.Indented
};
It should produce indented JSON for all your Web API endpoints.
Then you can inspect resulting JSON directly in browser or using some HTTP traffic capturing tool like Fiddler.
Use the JavaScript JSON.Stringify() function. Example:
$.ajax({
method: "POST",
url: "/yourController/yourAction",
data: { name: "John", location: "Boston" }
}).done(function( data ) {
alert(JSON.Stringify(data));
});