Reading JSON in Javascript - 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]

Related

How can i get an index of an Array in an Array of a Json Doc

I have a Json Doc which i get from my back end which looks like the one below. It has an emails Array which the doc under it has and email array. I need to get the index the email array is part of which has a match for an email address so i can update the doc. i used lodash before to search for a key in a array of docs before with _.find and _.indexOf but not sure how this would work in an Array of Array case.
{
"_type": "email_campaign",
"status": "Active",
"start_date": "04/17/2020",
"template_id": "template::0a2decdd-3acd-4661-9721-1a9ec0d039e6",
"summary": "Update",
"metrics": {
"first_email_sent": "",
"last_email_send": "2020-04-17T22:11:52.317Z",
"nbr_of_emails": 185,
"nbr_of_bounces": 1,
},
"history": {
"created_on": "04/17/2020 13:24:33",
},
"emails": [
{
"email": [
"DCustomer#gmail.com"
],
"track_request": "track_request::da07bd4b-b03e-4ecc-9d90-32e85cdb5b3a",
"tracking_nbr": "MD1dpjR6d"
},
{
"email": [
"ACustomer#matcocomponents.com",
"BCustomer#matcocomponents.com",
],
"track_request": "track_request::6f64cee1-d38e-4d68-94a2-c3c7d1287984",
"tracking_nbr": "YM1sMRX3nl"
},
{
"email": [
"ACustomer#gmail.com"
],
"track_request": "track_request::92606d4f-f9e6-457f-9156-167eb068f05b",
"tracking_nbr": "gj6dwIyHdE"
},
],
"_id": "3ed76589-4063-49f6-a21e-9ca16981d102"
}
You could use findIndex and includes:
const index = docs.emails.findIndex(item => item.email.includes('ACustomer#matcocomponents.com'))
try this:
emailToFind="xxxxxxxxx"
var indexes=[]
var test= res.emails.map((el1,i1)=>{
el.email.map((el2,i2)=>{
if (el2===emailToFind){
indexes.push(i1)
}
})
})

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

Reading Json file in php (or javascript) with sub array

This is my json file maps.json
[{
"type": "FeatureCollection",
"name": "maps",
"crs": { "type": "name", "properties": { "name": "urn:ogc:def:crs:OGC:1.3:CRS84" } },
"features": [
{ "type": "Feature", "properties":
{ "IDLo": "1", "SoHieu": "1-1", "KyHieu": "C", "TenLo": "C1-1", "TenCty": "CMC Data Center"},
"geometry": { "type": "Polygon", "coordinates": [ [ [ 106.791800519464871, 10.854928689692501 ],
[ 106.792069337729856, 10.855930098557222 ],
[ 106.792653322236532, 10.855766231881775 ],
[ 106.79231961680415, 10.854783029941672 ],
[ 106.791800519464871, 10.854928689692501 ] ] ] } },
{ "type": "Feature", "properties":
{ "IDLo": "2", "SoHieu": "1-2", "KyHieu": "C", "TenLo": "C1-2", "TenCty": "ASCENDAS" },
"geometry": { "type": "Polygon", "coordinates": [ [ [ 106.79264868743887, 10.855779887550094 ],
[ 106.792064702932166, 10.855943754285464 ],
[ 106.791786615071828, 10.854942345054598 ],
[ 106.79101723865827, 10.855151730898562 ],
[ 106.790461062937595, 10.855306494254153 ],
[ 106.789969774384346, 10.855424842648457 ],
[ 106.789478485831097, 10.855688850436046 ],
[ 106.78819928167357, 10.857819111634392 ],
[ 106.790915273109462, 10.859412245764197 ],
[ 106.791907119811313, 10.857746282442497 ],
[ 106.792111050908886, 10.857518691103408 ],
[ 106.792379869173871, 10.857291099590915 ],
[ 106.792583800271444, 10.856999782201919 ],
[ 106.792732113796944, 10.856544598212894 ],
[ 106.792741383392297, 10.856116724630859 ],
[ 106.79264868743887, 10.855779887550094 ] ] ] } }
]}]
I don't know how to read it til "TenCty": "CMC Data Center", and how can I replace "CMC Data Center" with something else and save it in maps.json file.
When users submit a form, information will save in MySqli and also save in json file? Is it possible? In javascript or PHP will ok.
This json file is map's information to show in Leaflet, so I must save as json. Any sugguestions? And thanks in advance
You need to complete a couple of steps.
First get the contents of the json file:
$contents = file_get_contents('maps.json');
Then apply json_decode() and convert to array:
$contents_decoded = json_decode($contents, true);
Now you can get "TenCty": "CMC Data Center":
echo $contents_decoded[0]['features'][0]['properties']['TenCty']; //CMC Data Center
You can replace the value:
$contents_decoded[0]['features'][0]['properties']['TenCty'] = 'something else';
Now you can encode the new array:
$contents = json_encode($contents_decoded);
echo $contents;
Output:
[{"type":"FeatureCollection","name":"maps","crs":{"type":"name","properties":{"name":"urn:ogc:def:crs:OGC:1.3:CRS84"}},"features":[{"type":"Feature","properties":{"IDLo":"1","SoHieu":"1-1","KyHieu":"C","TenLo":"C1-1","TenCty":"something else"},"geometry":{"type":"Polygon","coordinates":[[[106.79180051946487,10.854928689692501],[106.79206933772986,10.855930098557222],[106.79265332223653,10.855766231881775],[106.79231961680415,10.854783029941672],[106.79180051946487,10.854928689692501]]]}},{"type":"Feature","properties":{"IDLo":"2","SoHieu":"1-2","KyHieu":"C","TenLo":"C1-2","TenCty":"ASCENDAS"},"geometry":{"type":"Polygon","coordinates":[[[106.79264868743887,10.855779887550094],[106.79206470293217,10.855943754285464],[106.79178661507183,10.854942345054598],[106.79101723865827,10.855151730898562],[106.7904610629376,10.855306494254153],[106.78996977438435,10.855424842648457],[106.7894784858311,10.855688850436046],[106.78819928167357,10.857819111634392],[106.79091527310946,10.859412245764197],[106.79190711981131,10.857746282442497],[106.79211105090889,10.857518691103408],[106.79237986917387,10.857291099590915],[106.79258380027144,10.85699978220192],[106.79273211379694,10.856544598212894],[106.7927413833923,10.856116724630859],[106.79264868743887,10.855779887550094]]]}}]}]
The final step is you can put the new contents back to the maps.json file:
file_put_contents('maps.json', $contents);

How may I create an array of JSON objects?

Each object represents a different user and each user has 3 properties: loginid, password, realname.
Below is what I have written. Is this cord correct?
var user= [
{"loginid":"email1#email.com", "password":1234, "realname":"A" };,
{"loginid":"email2#email.com", "password":1234, "realname":"B" };,
{"loginid":"email3#email.com", "password":1234, "realname":"C" };,
]
Like LGSon said, you need to drop the ; from each line. Also you can define field namaes without " ", like this:
var user= [
{loginid:"email1#email.com", password:1234, realname:"A" },
{loginid:"email2#email.com", password:1234, realname:"B" },
{loginid:"email3#email.com", password:1234, realname:"C" },
]
I believe this is what you want:
var user= [
{loginid:"email1#email.com", password:1234, realname:"A"},
{loginid:"email2#email.com", password:1234, realname:"B"},
{loginid:"email3#email.com", password:1234, realname:"C"},
];
that's how you can create array object JSON
{
"user": [{
"loginid": "email1#email.com",
"password": 1234,
"realname": "A"
},
{
"loginid": "email2#email.com",
"password": 1234,
"realname": "B"
},
{
"loginid": "email3#email.com",
"password": 1234,
"realname": "C"
}
]
}
It is correct, except the semicolons.
EDIT:
Actually, I think the correct way would be
{ "users": [
{"loginid":"email1#email.com", "password":1234, "realname":"A" },
{"loginid":"email2#email.com", "password":1234, "realname":"B" },
{"loginid":"email3#email.com", "password":1234, "realname":"C" },
]
}

Remove String from JSON

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"}]"

Categories