Reading JSON file with different datatypes - json

I am trying to read a JSON file that contains following data
"{\"studentData\":[{\"Name\":\"Graham\",\"aggregate\":\"86\",\"regular\":\"true\",\"percentages\":[{\"sub1\":\"69\",\"sub2\":\"97\",\"sub3\":\"90\"}]},{\"Name\":\"Finley\",\"aggregate\":\"96\",\"regular\":\"false\",\"percentages\":[{\"sub1\":\"95\",\"sub2\":\"91\",\"sub3\":\"73\"}]},{\"Name\":\"Carrillo\",\"aggregate\":\"93\",\"regular\":\"true\",\"percentages\":[{\"sub1\":\"90\",\"sub2\":\"84\",\"sub3\":\"80\"}]},{\"Name\":\"Crosby\",\"aggregate\":\"68\",\"regular\":\"true\",\"percentages\":[{\"sub1\":\"63\",\"sub2\":\"92\",\"sub3\":\"77\"}]},{\"Name\":\"Small\",\"aggregate\":\"88\",\"regular\":\"true\",\"percentages\":[{\"sub1\":\"65\",\"sub2\":\"80\",\"sub3\":\"81\"}]}]}"
I have following code so far
const data = require("./testdata.json");
/*Explore the JSON file and return required JSON data*/
console.log(data)
when I run the code, I see the output in console
But how do I refer to each item in the data
e.g. Name, Regular
When I try to access using below code,
console.log(data.studentData.Name)
I get error
console.log(data.studentData.Name)
^
TypeError: Cannot read property 'Name' of undefined

data.studentData is an array so you need to loop through each value.
With forEach for example:
data.studentData.forEach((individualStudentData) => {
console.log(individualStudentData.Name);
//Do your thing (:
});
Or:
for (let individualStudentData of data.studentData)
a function like .map(() => { ... }
etc. ;)

It looks like data.studentData is actually a JSON Array. So if you wanted to log every name, you'd need to do
const data = require("./testdata.json");
data.studentData.forEach( student => console.log(student.Name));

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

want read a specific item from data() method in firestore

snapshot.forEach(doc => {
console.log("ID: "+doc.id, '=>', "Doc DATA: "+JSON.stringify(doc.data()));
});
I want to read only 1 item from doc.data() and that is an array of strings called ("supportedCurrencies").
How do i read? I'm new to firestore and TS so any help much appreciated.
Thanks!
When you call doc.data() you get a plain JavaScript object whose properties are each of the fields in the document:
const data = doc.data();
If you want one of those fields, just access it by name as a property of that object:
const supportedCurrencies = data.supportedCurrencies;
If it's an array, then you can treat it just like any other JavaScript array object.

Asserting entire response body in post man

I recently started working on spring boot projects.
I am looking for a way to assert the entire response of my API.
The intention of this is to reduce the testing time taken for the API.
Found A few solutions mentioned below, but nothing helped me resolve the issue.
pm.test("Body matches string", function () {
pm.expect(pm.response.text()).to.include("string_you_want_to_search");
});
pm.test("Body is correct", function () {
pm.response.to.have.body("response_body_string");
});
When I put the entire response body as an argument, I get the below errors.
Unclosed String
2.
3.
If you want to use the same type of quotes you defined the string with inside it, you have to escape them:
'string with "quotes"'
"string with 'quotes'"
'string with \'quotes\''
"string with \"quotes\""
You probably want to put your json in single quotes as they are not allowed by json itself.
You could try setting the response as a variable and then assert against that?
var jsonData = pm.response.json()
pm.environment.set('responseData', JSON.stringify(jsonData))
From here you can get the data JSON.parse(pm.enviroment.get('responseData')) and then use this within any test to assert against all of the values.
pm.test("Body is correct", () => {
var jsonData = pm.response.json()
pm.expect(jsonData).to.deep.equal(JSON.parse(pm.environment.get('responseData')))
})
My reasoning is that you’re trying to assert against JSON anyway but doing as a plain text string.
Or you could assert against the values separately like this:
pm.test("Body is correct", () => {
var jsonData = pm.response.json()
pm.expect(jsonData[0].employeeName).to.equal("tushar")
pm.expect(jsonData[0].phNum).to.equal(10101010)
})
Depending on the JSON structure you may not need to access an array of data and the [0] can be dropped.

displaying JSON onto Html - Angular 4

I have JSON data that I can read and access in console. I need to read onto Html. But it looks like I can't read. I get an error saying that cannot read property of NewDataSet. Anyone has ideas? I am not sure if data is returning from mpa function to subscribe.
html
<div>{{results.NewDataSet.Table[0]}}</div>
**sample data when returning res in service.ts **
Try this :
<div>{{results?.NewDataSet?.Table[0] | json}}</div>
Instead of
<div>{{results.NewDataSet.Table[0]}}</div>
your html page will rendered before your data populates by rest call response.
in that scenario your results variable is empty array without NewDataSet
results: any [];
so declare as object and create array as element of that object
results: any = { NewDataSet : {
Table : []
}
};
Change your declaration like this.

How to print an object as JSON to console in Angular2?

I'm using a service to load my form data into an array in my angular2 app.
The data is stored like this:
arr = []
arr.push({title:name})
When I do a console.log(arr), it is shown as Object. What I need is to see it
as [ { 'title':name } ]. How can I achieve that?
you may use below,
JSON.stringify({ data: arr}, null, 4);
this will nicely format your data with indentation.
To print out readable information. You can use console.table() which is much easier to read than JSON:
console.table(data);
This function takes one mandatory argument data, which must be an array or an object, and one additional optional parameter columns.
It logs data as a table. Each element in the array (or enumerable property if data is an object) will be a row in the table
Example:
first convert your JSON string to Object using .parse() method and then you can print it in console using console.table('parsed sring goes here').
e.g.
const data = JSON.parse(jsonString);
console.table(data);
Please try using the JSON Pipe operator in the HTML file. As the JSON info was needed only for debugging purposes, this method was suitable for me. Sample given below:
<p>{{arr | json}}</p>
You could log each element of the array separately
arr.forEach(function(e){console.log(e)});
Since your array has just one element, this is the same as logging {'title':name}
you can print any object
console.log(this.anyObject);
when you write
console.log('any object' + this.anyObject);
this will print
any object [object Object]