Remove String from JSON - javascript

I want to feed a dijit.form.Select (Dojo Select-Box) with a Data-Store (JsonRest). The Problem is, that the JSON-Parser only accepts JSON in this format:
[
{id:"1", name:"One1"},
{id:"2", name:"Two1"}
];
The REST-API of the webapplication we want to call delivers the following JSON:
{
"data": [
{id:"1", name:"One1"},
{id:"2", name:"Two1"}
],
"total": 2,
"start": 0,
"sort": "name",
"order": "asc",
"size": 2
};
That is why the Select Box does not show any data. Therefore, we need to remove the {"data": part and the last part of the JSON message bevore passing it to the Dojo Select Box.
The Data is stored in a JsonRest Object. So the question is how we can remove the first and the last part of the JSON in a way that simply this here is given to the Select-Box:
[
{id:"1", name:"One1"},
{id:"2", name:"Two1"}
];
Thank you for your answers and best regards
Ben

Create a new Array variable from the data for the dojo select seems simplest ...
var restapidataObj = {
"data": [
{id:"1", name:"One1"},
{id:"2", name:"Two1"}
],
"total": 2,
"start": 0,
"sort": "name",
"order": "asc",
"size": 2
};
var dojoSelectArray = restapidataObj.data;
Now pass dojoSelectArray to dojo

Store the result in a object and access the data property of that object.
var result = {
"data": [
{id:"1", name:"One1"},
{id:"2", name:"Two1"}
],
"total": 2,
"start": 0,
"sort": "name",
"order": "asc",
"size": 2
};
result.data would give you the data array.
Check the javascript object documentation at MDN

resultFromServer =
{
"data": [
{id:"1", name:"One1"},
{id:"2", name:"Two1"}
],
"total": 2,
"start": 0,
"sort": "name",
"order": "asc",
"size": 2
};
this convert to object (Use this incase resultFromServer is a string)
var Output = eval('('+ resultFromServer+')')
this gives your output
JSON.stringify(Output.data)
gives the string
"[{"id":"1","name":"One1"},{"id":"2","name":"Two1"}]"

Related

How To Remove Nested Array In React Native

I don't know how to remove the nested array in react native. Example :
Array [
Array [
Array [
"77",
undefined,
"Double Pixel Chart",
"c1",
"Chart",
],
Array [
"78",
undefined,
"Heikin Ashi Chart",
"c2",
"Chart",
],
],
]
What I want is just this array structure :
Array [
"77",
undefined,
"Double Pixel Chart",
"c1",
"Chart",
],
Array [
"78",
undefined,
"Heikin Ashi Chart",
"c2",
"Chart",
],
This is my code for pushing into the array :
for (let menu of response.data.Data) {
apiChartingMenu = new ApiChartingMenuModel (
menu.idx,
menu.shortDescription,
menu.titlecommand,
menu.command,
menu.commandtype,
);
data.push(Object.values(apiChartingMenu));
}
How can I achieve this?
You can use plain Javascript by using array.flat(). For your case this could be done as follows.
array = [
[
[
"77",
undefined,
"Double Pixel Chart",
"c1",
"Chart",
],
[
"78",
undefined,
"Heikin Ashi Chart",
"c2",
"Chart",
],
]
]
console.log(array.flat())
In your case you could make it work by either using
data.push(Object.values(apiChartingMenu).flat());
or by not introducing the object ApiChartingMenuModel at all, since you are just using its values anyway. This could also be done as follows.
// dummy menu object
menu = {
idx: 77,
shortDescription: "description",
titlecommand: undefined,
command: undefined,
commandtype: undefined
}
data = []
data.push([menu.idx, menu.shortDescription, menu.titlecommand, menu.command, menu.commandtype])
console.log(data)

PHP JSON Array to Javascript decoding

I have the following json which is returned by Influxdb which I can decode with PHP with out any issue i.e I use the following code:
$json_result = json_decode($json_result, true);
$http_result_series_0 = $json_result["results"][0]["series"][0] ["values"][0][5];
Now I would like to do the decoding with javascript in order to dynamically fill a table. But no matter how I try to do it, it's not working. I know that there's a similar way in javascript to decode the Array i.e:
json_result.results[0].series[0].values[0][5]
The json:
"{
"results": [
{
"statement_id": 0,
"series": [
{
"name": "default_lte_stick_1_test.com_http_response",
"tags": {
"server": "https://twitter.com"
},
"columns": [
"time",
"host",
"http_response_code",
"method",
"response_time",
"result",
"result_code",
"result_type",
"status_code",
"tag1",
"tag2"
],
"values": [
[
"2018-10-12T11:19:12Z",
"xps",
200,
"GET",
1.358607871,
"success",
0,
"success",
"200",
"test.com",
"LTE"
]
]
},
{
"name": "default_lte_stick_1_test.com_http_response",
"tags": {
"server": "https://google.com"
},
"columns": [
"time",
"host",
"http_response_code",
"method",
"response_time",
"result",
"result_code",
"result_type",
"status_code",
"tag1",
"tag2"
],
"values": [
[
"2018-10-12T11:19:10Z",
"xps",
301,
"GET",
0.051518655,
"success",
0,
"success",
"301",
"test.com",
"LTE"
]
]
},
{
"name": "default_lte_stick_1_test.com_http_response",
"tags": {
"server": "https://amazon.com"
},
"columns": [
"time",
"host",
"http_response_code",
"method",
"response_time",
"result",
"result_code",
"result_type",
"status_code",
"tag1",
"tag2"
],
"values": [
[
"2018-10-12T11:19:11Z",
"xps",
301,
"GET",
0.536477796,
"success",
0,
"success",
"301",
"test.com",
"LTE"
]
]
}
]
}
]
}
"
What I'm doing wrong? Every help is appreciated. Thanks!
EDIT:
The Influxdb API returns a pretty formated JSON. Currently I output the whole JSON with:
var json_result = '<?php echo $javascript_json_result;?>';
document.getElementById("jsonoutput").innerHTML = JSON.parse(json_result);
which outputs the whole json. But I would like to output only single values.
document.getElementById("jsonoutput").innerHTML = json_result.results[0].series[0].values[0][5]
trhows the following error:
e2e_check_new.php:172 Uncaught TypeError: Cannot read property '0' of undefined at e2e_check_new.php:172
What I'm doing wrong?
var json_result = '<?php echo $javascript_json_result;?>';
You are trying to output the JSON as a string in JavaScript by wrapping it in ' but you aren't escaping any of the characters in the JSON which have special meaning in JavaScript (like \ or a new line or ' - it looks like you definitely have at least new lines in your JSON).
Don't try to generate a string of JSON. Just output the JSON directly so it will be treated as a JavaScript object literal.
var my_object = <?php echo $javascript_json_result; ?>;
document.getElementById("jsonoutput").innerHTML = my_object;
… of course, this will convert the object to the string [Object object] which isn't useful. You can deal with the data structure in the usual ways though (i.e. access properties etc).

basic java script json child array decoding

I have been teaching myself some basic javascript the last couple of days and playing with google scripting as well as the twitter api and have come a bit unstuck on something that should probably be quite easy!
For sake of easierness of typing so my return from twitter api looks like this
[id:1
connections: "NONE"
],
[id:2
connections: ["following", "followed_by"]
]
What I am trying to do is find out out if the key 'following' exists for user 2, but I am really struggling!
The twitter api docs show an examples json as
[
{
"name": "Taylor Singletary",
"id_str": "819797",
"id": 819797,
"connections": [
"none"
],
"screen_name": "episod"
},
{
"name": "Twitter API",
"id_str": "6253282",
"id": 6253282,
"connections": [
"following",
"followed_by"
],
"screen_name": "twitterapi"
}
]
Can any point me in the correct direction?, how do I find out if following exists?
Thanks
connections: ["following", "followed_by"] is an array. To check if an array contains a special value you can use indexOf():
var a = [1, 2, "three", 44];
a.indexOf(1); // 0
a.indexOf(2); // 1
a.indexOf("three"); // 2
a.indexOf(22); // -1
So to check if "following" is in the array:
if (connections.indexOf("following") !== -1) {
// yeah!
} else {
// doh!
}
To count the objects in your example which have "following":
var o = [
{
"name": "Taylor Singletary",
"id_str": "819797",
"id": 819797,
"connections": [
"none"
],
"screen_name": "episod"
},
{
"name": "Twitter API",
"id_str": "6253282",
"id": 6253282,
"connections": [
"following",
"followed_by"
],
"screen_name": "twitterapi"
}
];
var withFollowing = o.filter(
function (i) {
return i.connections.indexOf("following") !== -1;
}
);
// filter() returns a new array
// this new array has only the elements for which the function returns true
console.log(withFollowing.lenght);

How to choose a json structure for data? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 9 years ago.
Improve this question
In this case the first variable is always the ID, the second variable is always the OCR number and the third number is always the amount. Then would it make any difference to do either in this way:
{
"Transactions": [
"23/2/2014 # 16:48:8",
[
[
"ID",
"1"
],
[
"OCR",
"123456789"
],
[
"Amount",
"100"
]
],
[
[
"ID",
"2"
],
[
"OCR",
"987654321"
],
[
"Amount",
"20"
]
]
]
}
Or the equivalent input with just the input data since we know that the index will be the same for the different values:
{
"Transactions": [
"23/2/2014 # 16:48:8",
[
[
"1"
],
[
"123456789"
],
[
"100"
]
],
[
[
"2"
],
[
"987654321"
],
[
"20"
]
]
]
}
Or even simpler:
{
"Transactions": [
"23/2/2014 # 16:48:8",
[
"1",
"123456789",
"100"
],
[
"2",
"987654321",
"20"
]
]
}
Or minimally:
{
"23/2/2014 # 16:48:8": [
[
"1",
"123456789",
"100"
],
[
"2",
"987654321",
"20"
]
]
}
But I don't thnk that the following is good style even though it would work if you know which element is which and just post an array:
{
"23/2/2014 # 16:48:8": [
123456789,
100,
987654321,
20
]
}
Or just an array (that is also valid json and contains all we need to know):
[
123456789,
100,
987654321,
20
]
Even though all the exampled appear to be valid json, it might be preferred to go in either direction, either a structure which is less readable and monimally just an array, or a structure that is named and more complex but also more readable even though a number can represent what time it is, it might be preferable to store it as a string and similar to have a label what some data is.
In my last example you must know that every second element is an amount and every other element is an OCR reference.
There is also an alternative that is valid json like this:
{
"23/2/2014 # 16:48:8": [
[
{
"OCR": 123456789
},
{
"Amount": 100
}
],
[
{
"OCR": 987654321
},
{
"Amount": 200
}
]
]
}
So I'm not sure how to represent the elements and lists.
Only you can decide what it should look like in the end, but here are a couple of suggestions...
Stay away from using data as keys...
{
"23/2/2014 # 16:48:8": []
}
Instead do something like this...
{
"timestamp": "23/2/2014 # 16:48:8",
"data": []
}
And your use of arrays seem better suited as objects. Here's an example of what I think is an acceptable representation...
{
"transactions": [
{ "id": 1, "timestamp": "23/2/2014 # 16:48:8", "ocr": 12345678, "amount": 500 },
{ "id": 2, "timestamp": "23/2/2014 # 16:48:9", "ocr": 345435, "amount": 200}
]
}
The best format really depends upon how you want to consume the data. But, generally I think of data like this as a collection of objects where each transaction is an object that has properties. In that vein, something like an array of transactions would make sense:
{
"Transactions": [
{
"time": "23/2/2014 # 16:48:8",
"id": "1",
"ocr": "123456789",
"amount": "100"
},
{
"time": "23/2/2014 # 16:48:8",
"id": "2",
"ocr": "987654321",
"amount": "200"
}
]
}
This lets you loop through the transactions and then access each of the properties of each transaction.

Reading JSON in Javascript

I am trying to parse some json that my server replies me.
I am getting this answer from the server:
{
"ROWCOUNT": 1,
"COLUMNS": [
"REGISTRATION_DT",
"USERNAME",
"PASSWORD",
"FNAME",
"LNAME",
"EMAIL",
"MOBILE",
"FACEBOOK_ID"
],
"DATA": {
"REGISTRATION_DT": [
"March, 17 2012 16:18:00"
],
"USERNAME": [
"user"
],
"PASSWORD": [
pass
],
"FNAME": [
"name"
],
"LNAME": [
"lname"
],
"EMAIL": [
"somemail"
],
"MOBILE": [
mobile
],
"FACEBOOK_ID": [
"fbid"
]
}
}
I am trying to extract the data with this way:
var xml2 = this.responseData;
var xml3 = JSON.parse(xml2);
Ti.API.log(xml3.DATA[0].FNAME);
What I am doing wrong here?
You're reading your JSON wrong. DATA is an object of arrays and not vica versa.
Ti.API.log( xml3.DATA.FNAME[0] );
Ti.API.log(xml3.DATA.FNAME[0]);
Two fields come without quotes:
"PASSWORD": [
pass
]
And
"MOBILE": [
mobile
],
xml3.DATA is an object, not an array.
You need to write
xml3.DATA.FNAME[0]

Categories