Converting xml text from webpage to json - json

I'm trying to convert xml on a webpage to json.
I used axios to grab the information from the URL and then used npm xml.js to try to convert the data to json.
let axios = require("axios");
let convert = require("xml-js");
let mtaURL = "http://advisory.mtanyct.info/eedevwebsvc/allequipments.aspx";
axios.get(mtaURL)
.then(response => {
let results = convert.xml2json(response, {compact: false, spaces: 4})
console.log(results);
})
It came back with the following:
Error: Text data outside of root node.
Line: 0
Column: 59
Char: x

You're trying to parse the Axios response object as XML.
You need to read the body of the response and treat that as XML.
response.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)
}
}

Angular 6: SyntaxError: Unexpected token O in JSON at position 0 at JSON.parse with valid 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);
}

Extract data from javascript

have a java script element , which when printed, gives [object Object].
console.log(data)
When i tried to JSON.Stringify(data) -it gives a json value:
{"key":"value"}
How to extract the value from the above object ?
JSON.stringify creates a JSON string representation of that JS object. If you want to use it as a JSON, you'd have to parse it again:
let data = '{"key": "value"}';
let dataJSON = JSON.parse(data);
console.log(dataJSON.key);
Outputs: value

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);

NodeJS JSON file Read without newline characters

I am reading a JSON file using fs.readFileSync(fileName, 'utf8'); but the results include newline characters, and the output is getting like:
"{\r\n \"name\":\"Arka\",\r\n \"id\": \"13\"\r\n}"
How do I avoid these characters?
my local file looks like:
{
"name":"Arka",
"id": "13"
}
Its unnecessary to read JSON in using fs.readFileSync(). This requires you to also write a try/catch block around the fs.readFileSync() usage and then use JSON.parse() on the file data. Instead you can require JSON files in Node as if they were packages. They will get parsed as if you read the file in as a string and then used JSON.parse(), this simplifies the reading of JSON to one line.
let data = require(fileName)
console.log(data) // { name: 'Arka', id: '13' }
If you want to serialize the parsed JS object within data to a file without the new line & carriage return characters you can write the JSON string to a file using JSON.stringify() only passing in data.
const {promisify} = require('util')
const writeFile = util.promisify(require('fs').writeFile)
const data = require(fileName)
const serializeJSON = (dest, toJson) => writeFile(dest, JSON.stringify(toJson))
serializeJSON('./stringify-data.json', data)
.then(() => console.log('JSON written Successfully'))
.catch(err => console.log('Could not write JSON', err))
You could read the file and then remove them with a regex:
var rawJson = fs.readFileSync(fileName, 'utf8');
rawJson = rawJson.replace(/\r|\n/g, '');
Keep in mind though that for parsing JSON with JSON.parse, you don't need to do this. The result will be the same with and without the newlines.