I need to show object_id of each object(response) from the following data.
This is the response i'm getting through Api. Suggestion or solution both will be well appreciated.
response:{"object_id":"a9951ef0","datetime":"2019-03-20T04:59:23.001Z","ignition_status":"ON"}
response:{"object_id":"8b1546924063","datetime":"2019-03-20T04:59:23.001Z","ignition_status":"OFF"}
response:{"object_id":"9b9d","datetime":"2019-03-20T04:59:23.001Z","ignition_status":"ONLINE"}
Expected output :
object_id = a9951ef0
object_id = 8b1546924063
object_id = 9b9d
I assume that you have 3 different responses with common key in them and you want to take the value of common key from them
If am correct you can you use streams.
Convert the json responses to List of objects
[
"response1",
"response2",
"response3"
]
arrayList = new Gson().fromJson(<above json>, ArrayList.class)
Then you can get expected values using streams
arrayList.stream.map(<arraylistType> :: <keyName>).collect(Collectors.toList());
Your API is returning JSON, which is a string. You need to “parse” it into a JavaScript Object and then you can simply access the value at the desired key.
const parsedResponse = JSON.parse(response);
console.log(parsedResponse.object_id);
Following logic could work. The example in pseudo code. Not work directly.
# real_response is your message from API.
# Convert it into array by splitting newlines. Use different separator if needed.
responses_in_array = real_response.split("\n");
# Loop through every responses.
foreach(single_response in responses_in_array) {
# Clean responses before converting them into javascript objects.
clean_response = single_response.replace("response:", "");
real_object = JSON.Parse(clean_response);
// Do what ever you want. To access object_id, just call
// real_object.object_id.
//
// If needed, before cleaning line, check if it's not empty line.
}
When you have solved the basic logic to parse the message, you can find better ways or built-in functions that help you.
Solution: I've solved the issue by the following way. Now everything is working fine.
<script type="text/javascript">
document.getElementById('test').onclick = function() {
xhr = new XMLHttpRequest();
xhr.open("GET", "filename.json or api url", true);
//xhr.open("GET", "compose.json", true);
xhr.onprogress = function(e) {
var data = e.currentTarget.responseText;
console.clear();
var data = JSON.parse(JSON.stringify(data));
data = data.replace(/(\r\n|\n|\r)/gm, "#");
data = data.replace(/##response:/g, ",");
data = data.replace(/response:/g, "");
data = data.replace(/##/g, "");
data = data.replace(/\\n/g, "\\n")
.replace(/\\'/g, "\\'")
.replace(/\\"/g, '\\"')
.replace(/\\&/g, "\\&")
.replace(/\\r/g, "\\r")
.replace(/\\t/g, "\\t")
.replace(/\\b/g, "\\b")
.replace(/\\f/g, "\\f");
// remove non-printable and other non-valid JSON chars
data = "["+data.replace(/[\u0000-\u0019]+/g,"")+"]";
var data = JSON.parse(data);
console.log(data);
}
xhr.onreadystatechange = function() {
if (xhr.readyState == 4) {
console.log("Complete = " + xhr.responseText);
}
}
xhr.send();
};
</script>
Related
I try get the sessionid before REST function, but in the case if I does not convert toString(); show only numbers (21 22 2e ...).
See this image:
1º:
Obs.: Before using split.
!!xxxxxxx.xxxxx.xxxxxxx.rest.schema.xxxxResp {error: null, sessionID: qdaxxxxxxxxxxxxxj}
My code:
var Client = require('./lib/node-rest-client').Client;
var client = new Client();
var dataLogin = {
data: { "userName":"xxxxxxxx","password":"xxxxxxxx","platform":"xxxxx" },
headers: { "Content-Type": "application/json" }
};
client.registerMethod("postMethod", "xxxxxxxxxxx/login", "POST");
client.methods.postMethod(dataLogin, function (data, response) {
// parsed response body as js object
// console.log(data); all return, image 1
// raw response
if(Buffer.isBuffer(data)){
data = data.toString('utf8'); // if i does not convert to string, return numbers, see image 1..
console.log(data); //all inside image 2, and i want just value from sessionid
var output = data;
var res = output.split(" "); // using split
res = res[4].split("}", 1);
}
console.log(res); //image 3
});
I tested with JSON.parse and JSON.stringify and it did not work, show just 'undefined' for all. After convert toString();, And since I've turned the values into string, I thought of using split to get only the value of sessionid.
And when I used split, all transform to array and the return is from console.log(data), see image 2:
2º:
Obs.: After use split and convert to array automatically.
And the return after use split is with the conditions inside my code:
3º:
And the return after use split is with the conditions inside my code:
[ 'bkkRQxxxxxxxxxxxxx' ]
And I want just:
bkkRQxxxxxxxxxxxxx
I would like to know how to solve this after all these temptations, but if you have another way of getting the sessionid, I'd be happy to know.
Thanks advance!
After converting the Buffer to a string, remove anything attached to the front with using data.substr(data.indexOf('{')), then JSON.parse() the rest. Then you can just use the object to get the sessionID.
if(Buffer.isBuffer(data)){
data = data.toString('utf8');
data = data.substr(data.indexOf('{'));
obj = JSON.parse(data);
console.log(obj.sessionID);
}
EDIT:
The issue you are having with JSON.parse() is because what is being returned is not actually JSON. The JSON spec requires the properties to be quoted ("). See this article
If the string looked like this, it would work: {"error": null, "sessionID": qdaxxxxxxxxxxxxxj}
Because the json is not really json, you can use a regular expression to get the info you want. This should get it for you.
re = /(sessionID: )([^,}]*)/g;
match = re.exec(data);
console.log(match[2]);
EDIT 2: After fully reading the article that I linked above (oops haha), this is a more preferable way to deal with unquoted JSON.
var crappyJSON = '{ somePropertyWithoutQuotes: "theValue!" }';
var fixedJSON = crappyJSON.replace(/(['"])?([a-zA-Z0-9_]+)(['"])?:/g, '"$2": ');
var aNiceObject = JSON.parse(fixedJSON);
I'm using the jquery get() function to send data. The data was array with information that can have special characters like / , ? and " . When this happens i can't access to url because the characters spoil the link.
How can i solve that? I did this:
function exemple()
{
$('.add').click(function(e)
{
var kitFamilia = $('#select-family').val();
var kitReference = $('#referenceinput').val();
var kitDescription = $('#descriptioninput').val();
var kitModel = $('#model-input').val();
var supplier = $('#select-supplier').val();
var details = [];
//alert(data);
details.push({stamp: stamp,family: kitFamilia, reference: kitReference, description: kitDescription, model: kitModel, supplier: supplier});
details = JSON.stringify(details, null, 2);
//alert(details);
$.get("/management-kit/create-kit/"+details, function(data)
{
location.reload();
});
e.preventDefault();
});
}
You should encode the data with encodeURIComponent
$.get("/management-kit/create-kit/"+encodeURIComponent(details), ..
Keep in mind that you are sending the JSON encoded as part of the path and not as a parameter. (and you might also want to remove the 2 space formating of the JSON as it will make the url quite longer)
I'm getting a JSON response from my service. Following the tutorial, I created response for binding data in datatables jquery plugin.
Client Side code :
var test_reports = jsonResp.reports;
var aDataSet = [test_reports];
$('#example').dataTable( {
"aaData": aDataSet,
"aoColumns": [{ "sTitle": "Tests" },
{ "sTitle": "Reports"}]
});
In console, my "test_reports" shows :
['TEST_1','1'] ['TEST_2','1']
But while binding this data to tables, it throws error. If I copy this cosole output into aaData, it creates the table. I understood that my "test_reports" is a string and this plugin is expecting an array of values. Any ideas of making this work!!
Server side code which gives this json response :
testcasesCountRS = statement.executeQuery(testcasesQuery);
while(testcasesCountRS.next()){
String test_name = testcasesCountRS.getString("test_name");
String test_count = testcasesCountRS.getString("test_count");
testResults.put(test_name, test_count);
resBuffer.append("[\'" + test_name + "\',\'" + test_count + "\'],");
}
resBuffer = resBuffer.deleteCharAt(resBuffer.lastIndexOf(","));
reports.put("reports", resBuffer);
Is there any alternative in my server side code to send the response as an array object to the datatables plugin.
You server response should be an array of array.
[['TEST_1','1'],['TEST_2','1']]
Change your code to
resBuffer.append("[");
while(testcasesCountRS.next()){
String test_name = testcasesCountRS.getString("test_name");
String test_count = testcasesCountRS.getString("test_count");
testResults.put(test_name, test_count);
resBuffer.append("[\'" + test_name + "\',\'" + test_count + "\'],");
}
resBuffer = resBuffer.deleteCharAt(resBuffer.lastIndexOf(","));
resBuffer.append("]");
The above code is untested. But hope you get the idea.
Documentation link
I made it work the following way :
JSONArray testCaseArray = new JSONArray();
while(testcasesCountRS.next()){
JSONArray testCase = new JSONArray();
String test_name = testcasesCountRS.getString("test_name");
String test_count = testcasesCountRS.getString("test_count");
testCase.add(test_name);
testCase.add(test_count);
testCaseArray.add(testCase);
}
reports.put("reports", testCaseArray);
The only thing thats bothering me is, it so stupid code that I need to create a new Array every time in my loop. And adding these arrays to my main Array object. There should be some work around to make it simple. Please suggest some efficient methodology.
hi i have a page contains a link , when user click the link i want to go to database and retrieve two arrays , but when i alert those two arrays i got this exception
Unexpected token [
this is my js code
function acNewConcpet(element){
var parent = element.parentNode;
parent.removeChild(element);
var concpetSelect = document.createElement('select');
var relationSelect = document.createElement('select');
xmlhttp = new XMLHttpRequest();
xmlhttp.onreadystatechange=function(){
if(xmlhttp.readyState==4 && xmlhttp.status==200){
var data = JSON.parse(xmlhttp.responseText);
alert(data);
}
}
xmlhttp.open("GET","http://localhost/Mar7ba/Ontology/getRelatedConceptsAndRelations/"+"concept"+"/TRUE",true);
xmlhttp.send();
}
and this is my php code
public function getRelatedConceptsAndRelations($concpetName, $Ajax) {
if ($Ajax) {
$concepts = array('c1', 'c2');
$relations = array('r1','r2');
echo json_encode($concepts);
echo json_encode($relations);
}
return;
}
why is this exception ? and how can i solve it ? and how can i receive those two arrays in my js ?
this is full code code
JSON.parse can only parse a single JSON literal.
You should combine the two arrays into a single object with two properties.
You are returning malformed JSON. From what I understand from your code, it prints out this JSON:
['c1','c2']['r1,r2']
You cant have 2 arrays like this. You must print it like:
[['c1','c2'],['r1','r2']]
Sorry for my rusty PHP, but you must have something like:
$json = array(
array('c1','c2'),
array('r1','r2')
);
echo json_encode($json);
Since you are using jQuery, why not use $.getJSON()?
$.getJSON(url,function(returnData){
//returnData is the parsed JSON
});
When you response a JSON, it needs to be one JSON, but you are sending two seperate arrays.
Merge those two JSONs into one.
Update:
Do it like this:
public function getRelatedConceptsAndRelations($concpetName, $Ajax) {
if ($Ajax) {
$concepts = array('c1', 'c2');
$relations = array('r1','r2');
echo json_encode(array($concepts, $relations));
}
return;
}
I have a json arry
var students = {"apResults":[{"offid":"267","item_name":"","offer_name":"fsdfsf","stlongitude":"77.5945627","stlatitude":"12.9715987"},
{"offid":"265","item_name":"","offer_name":"vess offer shops","stlongitude":"","stlatitude":""},
{"offid":"264","item_name":"","offer_name":"vess ofer shop","stlongitude":"","stlatitude":""},
{"offid":"263","item_name":"","offer_name":"ofer frm vess","stlongitude":"77.5943760","stlatitude":"12.9716060"},
{"offid":"262","item_name":"","offer_name":"offer hungamma","stlongitude":"77.5943760","stlatitude":"12.9716060"},
{"offid":"261","item_name":"","offer_name":"offer hungamma","stlongitude":"77.5943760","stlatitude":"12.9716060"},
{"offid":"260","item_name":"","offer_name":"offer1","stlongitude":"77.5943760","stlatitude":"12.9716060"},
{"offid":"259","item_name":"","offer_name":"offer","stlongitude":"77.5943760","stlatitude":"12.9716060"}]}
How i can parse this json arry using json.parse. I have tried this code
for(i=0;i<students.apResults.length;i++)
{
var contact = JSON.parse(students.apResults);
var offid = contact.offid;
alert(offid)
}
But its giving an error JSON.parse: unexpected character.Edited my question
That's not a json string, that's a regular javascript variable:
for(i=0;i<students.Maths.length;i++)
{
var contact = students.Maths[i];
var fullname = contact.Name;
alert(fullname)
}
for(i=0;i<students.apResults.length;i++)
{
var contact = JSON.parse(students.apResults[i].offid);
alert(contact)
}
JSON parses strings, not objects/arrays.
why need parsing when you can access it like students.Maths[i].Name
students is not a JSON array, it's an actual array. You don't have to parse because it's not a string. So you can access directly to the data you need:
for(i=0;i<students.Maths.length;i++) {
var contact = students.Maths[i];
var fullname = contact.Name;
alert(fullname)
}
You can't parse students because is not a JSON. It's simple object.
However this will work:
var students = JSON.stringify(students); // if you want to send data
students = JSON.parse(students); // after receiving make a object from it
//use like any object
for(i=0;i<students.Maths.length;i++)
{
var contact = students.Maths[i];
var fullname = contact.Name;
alert(fullname)
}
Of course it doesn't make sense to write it that way unless you send students data to other site or program.
Edit:
You don't need JSON in this code at all. But if you want to test JSON.parse() do it this way:
var students = { ... } // your data
var students = JSON.stringify(students); // students is `object`, make it `string`
students = JSON.parse(students); // now you can parse it, `students` is object again
for(i=0;i<students.apResults.length;i++) {
var contact = students.apResults; // no JSON
var offid = contact.offid;
alert(offid)
}
That should work.
What you have is a javascript object. So, you won't need the JSON.parse
for(i=0;i<students.Maths.length;i++)
{
var contact = students.Maths[i]);
var fullname = contact.Name;
alert(fullname)
}
this should be ok
The idea of JSON is for the exchange of objects represented as a structured string (in a nutshell). What you've got there is simply an object. It's unnecessary (and impossible) to parse and object that isn't JSON into a javascript object; what you have is the outcome of what you would expect from a parsed JSON string.