Json obj is not acting correct way in javascript - javascript

I am trying to get form data to json object and modify it... But it is not working...
Here is my code-
let formData = new FormData(thisForm).entries();
let body = JSON.stringify(Object.fromEntries(formData));
console.log(body);
console.log(body.firstName);
console.log("service=" + body.service);
body.service = "hello";
the console.log(body) is printing output like this-
{"prospectType":"1","firstName":"Arnab","middleName":"","lastName":"Maiti","mobileNumber":"07xxxxxx","workPhoneNumber":"","sourceOther":"","streetArea":"Kanakpur","service":"OTT"}
But console.log(body.firstName); is printing undefined.
Same thing is happening for other things.. What is the problem?

It's because body is a string, not a JSON object, because you've JSON.stringify'd it.
Use JSON.parse instead to create a JSON object that you can edit like that.
var body = '{"prospectType":"1","firstName":"Arnab","middleName":"","lastName":"Maiti","mobileNumber":"07xxxxxx","workPhoneNumber":"","sourceOther":"","streetArea":"Kanakpur","service":"OTT"}';
var jsonBody = JSON.parse(body);
console.log(jsonBody.firstName);

Because you use JSON.stringify() on the object first.
You use that to transfer the object over http. Apply that later on and you're fine.

Related

How to read specific object from json file in JavaScript?

I'm trying to work with a json file but I can't figure out how to read just a specific object from a json file.
My current code looks like this:
try {
const data = fs.readFileSync("addresses.json", "utf8");
console.log(data);
} catch (err) {
console.error(err);
}
This works fine. However when I try to get some object from the file like this:
console.log(data.address)
It doesn't work because it is a string.
So my question is how can I read just a single object from the json file.
Thanks a lot!
Try:
const parsedData = JSON.parse(data)
const address = parsedData.address
You need to use JSON.parse(), as right now, you are trying to access a property off of a string. However, the method will change it to an object.
// Dummy JSON data
const data = `{ "address": "Stack Overflow" }`;
const json = JSON.parse(data);
console.log(json.address);
This will make it possible to access the properties off of the object.
you must convert the data into json like so:
JSON.parse(data)
In your example :
try {
const data = fs.readFileSync("addresses.json", "utf8");
console.log(JSON.parse(data).address);
} catch (err) {
console.error(err);
}
I hope I answered your question.
Feel free to comment if I misunderstood you or you have some questions ;)

Node.js: Parsing a json-ld / JSON with "#"-symbol

I have a JSON that looks like this:
{"marker":[{"#attributes":{"start":"Im Berge",
"finish":"Eichelberger Stra\u00dfe"
...
I am trying to parse the attributes inside the "#attributes", but have not found a way to do it. What I tried so far:
const fs = require('fs');
var jsonObj = JSON.parse(fs.readFileSync('route1.json', 'utf8'));
console.log(jsonObj['#attributes']);
Also tried the same with
console.log(jsonObj.marker['#attributes']);
Neither of which work. I understand that this is supposed to be a json-ld and that I'm supposed to parse an object with an "#" sign with ['#attributes'], but either way I always get an error or undefined. I got the JSON from an API I wanna use and it is in there multiple times, so I have no way around it.
.marker is an array so:
console.log(jsonObj.marker[0]['#attributes']);
But you may want to loop through it:
jsonObj.marker.forEach(marker => console.log(marker['#attributes']));
You can require a JSON file, instead of JSON.parse & fs.readFileSync
var jsonObj = require('./route1.json');

My code wont print my object

When I try to print my object it gives me no response.
var steaminv = JSON.parse("http://steamcommunity.com/id/pootel/inventory/json/730/2.json");
document.write(steaminv);
You should request the file first and then parse the content of the file.
JSON.parse requires a json object encoded as string. It does not request the file for you.
If you are using node, you can use request module. If you are using javascript on browser, you can use jQuery and do an ajax call to get the content of the file.
Please take a look at this question: How do I receive a JSON file using AJAX and parse it using javascript?
Just to give you an idea what JSON.parse does:
var str = '{"name":"Amir","age":25}';
var obj = JSON.parse(str);
console.log(obj.name);
console.log(obj.age);

xPages - set javascript variable by reading JSON from URL

I have an xAgent (based on JSONandRest example in openntf by Nikolas Heildoff) which returns me a json. this xpage is nothing by there is a call to java method which returns JSON.
My problem is to have this JSON read into a JS variable so I am able to play with it.
I would like to do something like:
var myJson = getJson("Json.xsp")
Thanks in advance
Arun
You can use the fromJson method:
var json = "{a:'123', b: 'abc'}";
var obj = fromJson( json );
println( obj.a );
This sends 123 to the console.

AJAX post JSON data from Javascript to Grails

I'm trying to POST JSON formatted data from Javascript (using Prototype) to Grails. My Javascript code is:
var JSONObject = new Object;
JSONObject.id = "23";
JSONObject.name = "Test 1";
JSONstring = JSON.stringify(JSONObject);
var url = "${createLink(controller:'testController', action:'receiveJson')}";
new Ajax.Request(url, {
method:'post',
contentType:'application/json',
parameters:JSONstring,
asynchronous:true,
onSuccess: function (req) {
sendInfoResponse(req.responseText);
}
});
and the code in my Grails controller is:
def receiveJson = {
def json = request.JSON;
}
However, the 'json' variable appears to be empty in my tests. I'd be so grateful if someone could explain what I'm doing wrong. Many thanks.
In your Ajax.Request options change
parameters:JSONstring,
to
postBody:JSONstring,
The problem with using parameters is that it URL encodes the data so that the request body ends up looking like this:
%7B%22id%22%3A%2223%22%2C%22name%22%3A%22Test%201%22%7D&_=
Instead of the desired (which is what you get with postBody):
{"id":"23","name":"Test 1"}
Good question mfloryan - I was doing the testing manually, i.e. not as part of a unit or integration test.
Thanks very much for the help hvgotcodes. I made the changes to my code as you have suggested, but unfortunately to no avail. Interestingly, if I print request.JSON I get {}, whereas if I print request.json I get null.
EDIT: By 'printing' I mean using: request.JSON.toString()
EDIT: Thank you all so much for the help. Once I'd made the final change John Wagenleitne suggested the code began working properly. I'm very grateful indeed for all your help.
I don't think you are invoking the Ajax.Request correctly. From the documentation, the parameters option:
"The parameters for the request, which will be encoded into the URL for a 'get' method, or into the request body for the other methods. This can be provided either as a URL-encoded string or as any Hash-compatible object (basically anything), with properties representing parameters."
I think you need to do something like
...
parameters: {json: JSONString}
...
and then in your controller
request.json
note the form of the parameters object literal - it tells the Prototype library to make the request key 'json' and the request value be the json string. You access the key off the request object in the controller.
EDIT -- I just realized you're javascript block is jacked up.
This:
var JSONObject = new Object;
should be something like
var JSONObject = new Object();
...
you might also be able to do just an object literal, so
var jsonObject = {};
....

Categories