Angular 6: SyntaxError: Unexpected token O in JSON at position 0 at JSON.parse with valid JSON - json

I am not sure whether my function is wrong, which should send data to the server, or the function on the server is wrong.
I looked up similar questions but the solution I adopted to my problem did not work.
My function looks like this:
postData(number){
let array = JSON.stringify(this.locArr);
return this.http.post<any>(this.url, array)
.subscribe(),
error => console.log("Error: ", error)
}
JSON which is send:
[
{
"id":222,
"name":"Lars",
"sLA":37
},
{
"id":223,
"name":"Sim",
"sLA":12
}
]
All parameters like token etc. are received by the server function but the array I wrote above is null, although it is valid json.
I wonder why this error is occuring.
Any advice is appreciated

The local array will be converted into JSON automatically by Angular, you need not stringify or parse it.
postData(number){
this.http.post<any>(this.url, this.locArr)
.subscribe((data)=>{
//code after receiving data from server
},
error => console.log("Error: ", error))
}

I believe you are using httpClientModule so then there is no need of tyou need't JSON.stringify remove this step JSON.stringify(this.locArr);
Also you need to send it as json object {} not json array []
postData($locArr){ // pass the array to the service function
let data = { data : $locArr}; // note that you have to post it as json object {} not []
return this.http.post<any>(this.url,data);
}

Related

typescript - load json from url and get access to array of json objects

I just can't find a working solution and implement in my format.
There is a JSON file which is returned to me by URL. Its format is:
{"success":true,
"data":[
{
"loadTimestamp":"2022-07-20T15:12:35.097Z",
"seqNum":"9480969",
"price":"45.7",
"quantity":"0.2",
"makerClientOrderId":"1658329838469",
"takerClientOrderId":"1658329934701"
},
{
"loadTimestamp":"2022-07-20T14:49:11.446Z",
"seqNum":"9480410",
"price":"46",
"quantity":"0.1",
"makerClientOrderId":"1658328403394",
"takerClientOrderId":"0"
}]
}
Due to the fact that it is returned via the URL, it is not possible to directly use the object, for example:
myobj['data']['price']
I have either a string of data that I can convert using JSON.parse() or an object right away.
But for some reason I can't use it directly.
As far as I understand, this is a JSON file inside which is an array of JSON data.
My goal is to display all the data from the array, while taking for example 2 values: price, quantity
How can I access the values that I want to get?
Ok I find, what I was looking for.
I return result not in json, but in text response.text()
After I did this, I create a new constant called res and put in it JSON.parse(data)
const url = 'https://myurl.com/'+pub_key
const response = await fetch(url)
let data = ''
if (response.ok) { data = await response.text() } else { console.log("Error HTTP: " + response.status) }
const res = JSON.parse(data)
After all this manipulations I can use my data with 2 ways:
console.log(res["data"][0]["price"])
console.log(res.data[0].price)
Or I can make a cocktail from it, by using my favorite blender :)))
if(res.success==true){
for(let item in res.data){
console.log(res.data[item].price,res.data[item].quantity)
}
}

parse json response to typescript class

i know there are multiple similar topics, however trying their solutions doesn't give me expected result.
Input json string
data:"{"message": "{\"type\":\"CONTROL\",\"command\":\"REQUEST_STATUS_ALL\"}"}"
object declaration/parse:
const msg: Message = <Message>JSON.parse(data.data);
output:
{message: "{"type":"CONTROL","command":"REQUEST_STATUS_ALL"}"}
-values are not properly assigned, but instead in a text form.
the same object looks like this if it's initialized manually(in TS):
MessageĀ {type: "CONTROL", status: undefined, command: "REQUEST_STATUS_ALL", body: undefined}
What is the correct way to parse that json string into the Message object?
Thank you!
It seems the value for message was improperly encoded as a string. Calling JSON.parse a second time on the message property will get the result you want, though you might want to fix the underlying cause of the improperly encoded data instead.
parseMessage(data: string) {
const msgTemp = JSON.parse(data);
msgTemp.message = JSON.parse(msgTemp.message);
return <Message>msgTemp;
}
const msg = parseMessage(data.data);

Not able to get value from Json key

I am trying to get an object from Mongoose but when I get it and try to access the Json object by key to get the value i get undefined.
User.find({name: 'auth'},function (err,obj) {
var authCode = JSON.stringify(obj);
console.log(authCode);
var parse = JSON.parse(authCode);
console.log(parse);
console.log(parse.code);
});
I get the following output:
[{"_id":"5a43b491734d1d45eaf2d00d","name":"auth","code":"nCAxOSrUMqxtxd8T"}]
[ { _id: '5a43b491734d1d45eaf2d00d',
name: 'auth',
code: 'nCAxOSrUMqxtxd8T' } ]
undefined
I have even tried console.log(parse['code'])and i still get undefined. Can someone please help me
parse variable above is not a dictionary itself, but an array containing a dictionary. What you should do to access the code field would be first access the dictionary and then get the code field like;
parse[0].code
or
parse[0]['code']
You need not parse or stringify the returned JSON object. You can use the JSON object as it is. Try below approach
User.find({name: 'auth'},function (err,obj) {
console.log(obj);
console.log(obj.code);// this will probably be undefined as find method returns array of objects ( correct me if iam wrong)
user.forEach(function(obj,index){
console.log("index: "+index);
console.log("obj: "+obj.code);
});
});
Using promises is a good way
User.find({name: 'auth'})
.then((user)=>{
console.log("find success");
console.log(user);
console.log(user.code); // would return undefined as User.find will return array of objects
user.forEach(function(obj,index){
console.log("index: "+index);
console.log("obj: "+obj.code);
});
})
.catch(()=> {
console.log("find failed");
});

Handle raw JSON string with node and express

I have a really simple endpoint defined in NodeJS using Express:
router.put("/test", this.test.bind(this));
public test(req: Request, res: Response, next: NextFunction) {
console.log(req.body);
}
The endpoint is working correctly if I PUT the following JSON body:
{
"name": "something"
}
However, if I use a JSON body without curly brackets (which is totally valid) like this:
"something"
I get an error:
TypeError: First argument must be a string or Buffer
at ServerResponse.OutgoingMessage.end (_http_outgoing.js:558:11)
Content-Type in both cases is application/json.
Why are these raw JSON strings not getting accepted and how can I solve this?

Convert JSON object to array?

I have this on my console on firebug,
[Object { fa_id="1167535", f_id="1000", loc_type="6", more...}, Object { fa_id="1167535", f_id="1000", loc_type="6", more...}]
it is data from the server side. Now, how would I convert this into array such that this data can be used on another file. I tried JSON.parse and jQuery.parseJSON but both did not work.
That isn't JSON it's a Javascript array of objects, not a string. My guess is that you've received this from a jQuery ajax call and you had the dataType : 'json' set so that jQuery has automatically parsed the JSON into this array.
To send it to a PHP script you can convert it back to JSON using:
var myString = JSON.stringify(data);
and then fire off an ajax call to the PHP script with that as the POST data:
var myString = JSON.stringify(data);
$.post('page.php', { data : myString }, function(){
console.log( "sent" );
});
In PHP you can decode it using:
$data = json_decode($_POST['data']); // <-- or whatever your post variable is named
foreach($data as $obj)
{
echo $obj->fa_id;
}
if you want to get an php array use this
http://php.net/manual/en/function.json-decode.php
The string you provided is not valid JSON.
[Object { fa_id="1167535", f_id="1000", loc_type="6", more...},
Object { fa_id="1167535", f_id="1000", loc_type="6", more...}]
In particular, the "Object" and "more..." strings cannot be interpreted by a JSON parser.
Assuming the object you are inspecting is a variable named foo:
console.log(JSON.stringify(foo));
Should print a valid JSON representation of your object to the Javascript console.