I am new to JSON and concepts. I want to extract the data from an API which i have mentioned below, basically i want to extract several details from this API about an Stock. The problem here is, after parsing the URL i dont know how to extract the value for each variablle.
I want to extract the data into an GoogleSheet.
the output of the below function shows, like this
[20-12-10 20:45:15:806 CET] [{symbol=JMIA, price=37.0497, volume=1.317713E7}]
The output i wanted is that:
JMIA
37.0497
1.317713E7
Code :
function CurrentPrice() {
var url = 'https://financialmodelingprep.com/api/v3/quote-short/JMIA?
apikey=7c2f5bcb573b33050c1aad41a54919';
var response = UrlFetchApp.fetch(url);
// convert json string to json object
var jsonSignal = JSON.parse(response);
Logger.log(jsonSignal);
}
I suggest you read this "Working with Objects" article.
The response is wrapped in brackets [] meaning it's an array. I assume you're only expecting one response, so you can grab that first element using jsonSignal[0], which will give you an object.
To get an object property, you have to specify the property name using either dot- or bracket-notation. (I'll use dot-notation.)
const jsonSignal = [{symbol:'JMIA', price:37.0497, volume:1.317713E7}];
console.log(jsonSignal[0].symbol); // 'JMIA'
function CurrentPrice() {
const url = 'https://financialmodelingprep.com/api/v3/quote-short/JMIA?apikey=API_KEY';
const response = UrlFetchApp.fetch(url);
// Convert HTTPResponse
// Use the first element in the response array
const signal = JSON.parse(response)[0];
console.log(signal.symbol); // 'JMIA'
console.log(signal.price); // 37.0497
console.log(signal.volume); // 1.317713E7
}
Try like this :
var json = response.getContentText();
var data = JSON.parse(json);
Logger.log(data);
I read that there : https://developers.google.com/apps-script/guides/services/external
Regards
I have a controller class in Spring MVC, where i am returning a HaspMap as Model attribute -
#ModelAttribute("regPrefix")
public Map<String, String> getRegPrefixesOfDepartmentforGroup(final Model model, final HttpServletRequest request) {
final Map<String, String> regPrefixOfDept = new HashMap<String, String>();
regPrefixOfDept.put(regKey, regPrefix);
return regPrefixOfDept;
}
Now in the corresponding JSP page, i am trying to access the Hashmap and store the key/value pairs of the Hasmap in a variable using JavaScript. I am trying like below but its not right. Can anyone suggest how to do that
<script>
$("#deptIdSelection").change(function()
{
var obj = document.getElementById("deptIdSelection");
var textItem = obj.options[obj.selectedIndex].text;
alert(textItem);
var mapObj = "${regPrefix}";
for(var key in mapObj)
alert(key +" ->"+ mapObj[key]);
}
);
</script>
Try to access map values like this:
${regPrefix.key}
If you want to iterate through the map keys, it is not so easy: JSTL is executed on the server side and is rendered to a plain text - no JavaScript objects are created. The following line var mapObj = "${regPrefix}"; will be rendered to a string representation of HashMap, not to a JavaScript object.
To convert your map to a JavaScript object I suggest you to use one of the following methods:
1) Convert your map to JSON and pass it as a String. So when it is rendered to a JavaScript code, it will look like a regular JS object: var mapObj = {"key": "value", ...};. You can use Gson or any other JSON library to achieve this:
final Map<String, String> regPrefixOfDept = new HashMap<String, String>();
regPrefixOfDept.put(regKey, new Gson().toJson(regPrefixOfDept));
And then var mapObj = ${regPrefix}; (note that you need no quotes around because you want mapObj to be a JS object, not a string)
2) Iterate through your map using <c:forEach> to generate a JS object:
var mapObj = {
<c:forEach items="${regPrefix}" var="item" varStatus="loop">
${item.key}: '${item.value}' ${not loop.last ? ',' : ''}
</c:forEach>
};
In both cases you should be able to then call
for(var key in mapObj)
alert(key +" ->"+ mapObj[key]);
guys i am using jqgrid .. here is my file
{
"rows":[
{"OrderID":"10248","FromDate":"1996-07-04","CustomerID":"WILMK","ShipName":"Vins et alcools Chevalier","ToDate":"1996-07-05"},
{"OrderID":"10249","FromDate":"1996-07-05","CustomerID":"TRADH","ShipName":"Toms Spezialit\u00e4ten","ToDate":"1996-07-17"},
{"OrderID":"10250","FromDate":"1996-07-08","CustomerID":"HANAR","ShipName":"Hanari Carnes","ToDate":"1996-07-26"},
{"OrderID":"10251","FromDate":"1996-07-08","CustomerID":"VICTE","ShipName":"Victuailles en stock","ToDate":"1996-08-01"},
{"OrderID":"10277","FromDate":"1996-08-09","CustomerID":"MORGK","ShipName":"Morgenstern Gesundkost","ToDate":"1996-08-12"}
]
}
but i want it to be like
{
"rows":[
{"OrderID":"10248","FromDate":"1996-07-04","CustomerID":"WILMK","ShipName":"Vins et alcools Chevalier","ToDate":"1996-07-05"},
{"OrderID":"10249","FromDate":"1996-07-05","CustomerID":"TRADH","ShipName":"Toms Spezialit\u00e4ten","ToDate":"1996-07-17"},
{"OrderID":"10250","FromDate":"1996-07-08","CustomerID":"HANAR","ShipName":"Hanari Carnes","ToDate":"1996-07-26"},
{"OrderID":"10251","FromDate":"1996-07-08","CustomerID":"VICTE","ShipName":"Victuailles en stock","ToDate":"1996-08-01"},
{"OrderID":"10277","FromDate":"1996-08-09","CustomerID":"MORGK","ShipName":"Morgenstern Gesundkost","ToDate":"1996-08-12"},
{"OrderID":"10261","FromDate":"1996-07-19","CustomerID":"QUEDE","ShipName":"Que Del\u00edcia","ToDate":"1996-08-09"} // added row
]
}
From your question it seems like, you want to add another object in json file within an array. So, here is a solution.
Read your json file with whatever library you are using to read/write json from files.
Add the new object in the specific list.
Write that to file with over write mode.
First parse your JSON content:
String input = "{\"rows\":[{\"OrderID\":\"10248\"}]}";
JSONObject json = new JSONObject(input);
Then get the array from the parsed content:
JSONArray arr = json.getJSONArray("rows");
Convert the object to add to JSON:
JSONObject newRow = new JSONObject();
newRow.accumulate("OrderID", 10000);
// Do the same for all your attributes
And finally add the new row to the array to get your updated JSON:
arr.put(newRow);
String updatedJSON = json.toString();
you want to add another object in json file within an array. So, here is a solution.
Read your json file.
Put your key row as a JSONArray and Store it into a String.
Construct a Class Order.
Class Order
{
String OrderID ;
String FromDate ;
String CustomerID
String ShipName;
String ToDate;
}
Add the new object in the specific list.
//import Class (add a jar com.fasterxml.jackson to your project)
import com.fasterxml.jackson.databind.ObjectMapper;
// Here I assume that "applicationArray" contains the Array .
String applicationArray = "[
{"OrderID":"10248","FromDate":"1996-07-04","CustomerID":"WILMK","ShipName":"Vins et alcools Chevalier","ToDate":"1996-07-05"},
{"OrderID":"10249","FromDate":"1996-07-05","CustomerID":"TRADH","ShipName":"Toms Spezialit\u00e4ten","ToDate":"1996-07-17"},
{"OrderID":"10250","FromDate":"1996-07-08","CustomerID":"HANAR","ShipName":"Hanari Carnes","ToDate":"1996-07-26"},
{"OrderID":"10251","FromDate":"1996-07-08","CustomerID":"VICTE","ShipName":"Victuailles en stock","ToDate":"1996-08-01"},
{"OrderID":"10277","FromDate":"1996-08-09","CustomerID":"MORGK","ShipName":"Morgenstern Gesundkost","ToDate":"1996-08-12"},
{"OrderID":"10261","FromDate":"1996-07-19","CustomerID":"QUEDE","ShipName":"Que Del\u00edcia","ToDate":"1996-08-09"} // added row
]"
ObjectMapper mapper = new ObjectMapper();
List<Order> obj_listOrder = mapper.readValue(applicationArray, mapper.getTypeFactory().constructCollectionType(List.class, DeviceApplication.class));
Now add one more element to the list .
Add One More element to the List.
Replace the content of Your file.
A list that contains a set of arrays is being serialized into jquery. However when check in client side, it is receiving only a string instead of the array object.
c#:
public string jsscript(){
// datatable processing
var arrList = new List<object>();
foreach (DataRow row in table.Rows)
{
string name = row[0].ToString();
string quantity = row[1].ToString();
string balance = row[2].ToString();
string remove = "X";
arrList.Add( new[] { name, quantity, balance, remove });
}
return (new JavaScriptSerializer()).Serialize(arrList);
}
js:
<script>
//dom...
function theDomHasLoaded(e) {
dbdata = <%=jsscripts()%>;
</script>
see JSON string to JS object
you need to use JSON.parse(..) on the serialised string
that is of course presuming that that is the problem... It's not entirely clear what your problem is.
I've got a function that queries my database and gets a list of usernames-- I've pasted it below:
*dbQuery.jsp*
<%!
org.json.JSONArray dbQuery(String SQL_STRING)
{
// This step will read hibernate.cfg.xml and prepare hibernate for use
org.hibernate.SessionFactory sessionFactory = new org.hibernate.cfg.Configuration().configure().buildSessionFactory();
org.hibernate.Session session1 = sessionFactory.openSession();
org.hibernate.Query query = session1.createQuery(SQL_STRING);
java.util.List list = query.list();
org.json.JSONArray jsonArray = new org.json.JSONArray(list);
// Actual contact insertion will happen at this step
session1.flush();
session1.close();
return jsonArray;
}
%>
I then try to parse through the list of users, but can't get it to work right. Here's what I'm doing:
var users = <%=dbQuery("FROM Users")%>;
alert("User= " + users[0].getAttribute('username'));
Why doesn't this work? What is the right syntax to parse through the objects/attributes in this JSON Array?
users[0].getAttribute('username')
will not work
try
users[0].username