problem parsing JSON Strings - javascript

var records = JSON.parse(JsonString);
for(var x=0;x<records.result.length;x++)
{
var record = records.result[x];
ht_text+="<b><p>"+(x+1)+" "
+record.EMPID+" "
+record.LOCNAME+" "
+record.DEPTNAME+" "
+record.CUSTNAME
+"<br/><br/><div class='slide'>"
+record.REPORT
+"</div></p></b><br/>";
}
The above code works fine when the JsonString contains an array of entities but fails for single entity. result is not identified as an array!
Whats wrong with it?
http://pastebin.com/hgyWw5hd

result is not an array. Do you see any square brackets in your JSON? no you do not. it does not contain any arrays.
{
"result": {
"ID": "30",
"EMPID": "1210308550",
"CUSTID": "1003",
"STATUS": "2",
"DATEREPORTED": "1273234502",
"REPORT": "this is one more report!",
"NAME": "Sandeep Savarla",
"CUSTNAME": "Collateral",
"LOCID": "4",
"LOCNAME": "Vijayawada",
"DEPTNAME": "SALES"
}
}
Can you show me what your "valid" json looks like when the function above works?

Just make sure it's an array before you iterate
if ( 'undefined' == typeof records.result.length )
{
records.result = [records.result];
}

Your code is looping through records.result as if it were an array.
Since it isn't an array, your code does not work.
This simplest solution is to force it into an array, like this:
var array = 'length' in records.result ? records.result : [ records.result ];
for(var x = 0; x < array.length; x++) {
var record = array[x];
...

In your code result is an object, not an array. Wrap it's value in square brackets to make it an array:
{
"result": [{
"ID": "30",
"EMPID": "1210308550",
"CUSTID": "1003",
"STATUS": "2",
"DATEREPORTED": "1273234502",
"REPORT": "this is one more report!",
"NAME": "Sandeep Savarla",
"CUSTNAME": "Collateral",
"LOCID": "4",
"LOCNAME": "Vijayawada",
"DEPTNAME": "SALES"
}]
}

Related

How can I merge and match 2 separate objects?

What I want
I have 2 different Java-Script arrays/objects but with matching Ids. I want to merge them into a new object. So both the main object data and any matched elements from the secondary object are merged into a combined result.
What I tried
I tried using Object.assign() function but with no success.
Given Input
Example code, so I have 2 separate objects (main and lines):
let main = [
{
"Id": "1",
"Name": "Testing data"
}
]
let lines = [
{
"OtherId": "1",
"code": "AU-29830"
},
{
"OtherId": "1",
"code": "AU-29854-Single"
},
{
"OtherId": "1",
"code": "TV-BB21084623"
},
{
"OtherId": "2",
"code": "Don't Merge"
},
{
"OtherId": "3",
"code": "Don't Merge"
}
]
Expected Output
I want to merge those 2 arrays, so that the output should be a single array containing the merged main-object. This merged main-object should contain the original content of itself plus nested the filtered secondary array (only containing matching objects). The filtering was done using the id from the main array's object which has to match (the slightly deviating id) from each object of the secondary-array.
The resulting array should look like this:
let result = [
{
"Id": "1",
"Name": "Testing data",
"lines": [
{
"OtherId": "1",
"ProductCode": "AU-29830"
},
{
"OtherId": "1",
"ProductCode": "AU-29854-Single"
},
{
"OtherId": "1",
"ProductCode": "TV-BB21084623"
}
]
}
]
As your main is an array, I'm assuming you might end up with more than one main item in it. If so, here's one way to merge your line items onto each one:
const mergedMainItems =
main.map(mainItem=>({
...mainItem,
lines: lines.filter(line=>mainItem["Id"] === line["OtherId"])
}))
I think for this example this will work:
let result = [];
result.push({...main[0]}); //or even result.push(main[0])
result[0].lines = [];
for(let l in lines){
if(lines[l].code != "Don't Merge"){
result[0].lines.push({OtherId: lines[l].OtherId, ProductCode: lines[l].code})
}
}

How to use jquery to handle multiple json objects

I am developing a website with front-end and back-end separated. I used jquery to send request and get the result as a json object:
{
"item": [
],
"shop": [
],
"user": [
{
"user_id": "9",
"full_name": "Minh Duc",
"email": "nguyenminhduc1803#gmail.com",
"fb_link": "https:\/\/www.facebook.com\/SieuNhan183",
"user_name": "Duc",
"password": "37cd769165eef9ba6ac6b4a0fdb7ef36",
"level": "0",
"admin": "0",
"dob": "1996-03-18",
"location": "Ho Chi Minh",
"user_image_url": null
}
]
}
Now i am finding a way to get the data from the object user. How can i do it with javascript?
Complementing #arcs answer, remember that in Javascript you can access members of an object using dot notation (data.user[0].user_id) or square brackets notation. This way:
data['user'][0]['user_id']
this is useful because you can have a 'class' array and then do things like:
['item', 'shop', 'user'].forEach((array) => processArray(data[array][0]));
then you can filter only some classes or do more advanced stuff
When you have the data (in example it's in data) use the dot notation to get the node with the user.
The user is an array, so use [] to access a single element, e.g. [0]
var data = {
"item": [
],
"shop": [
],
"user": [
{
"user_id": "9",
"full_name": "Minh Duc",
"email": "nguyenminhduc1803#gmail.com",
"fb_link": "https:\/\/www.facebook.com\/SieuNhan183",
"user_name": "Duc",
"password": "37cd769165eef9ba6ac6b4a0fdb7ef36",
"level": "0",
"admin": "0",
"dob": "1996-03-18",
"location": "Ho Chi Minh",
"user_image_url": null
}
]
}
console.log( data.user[0].user_id )
I prefer use square brackets like this :
$jsonObject["user"][0]["user_id"]
but you can use the dot like this :
data.user[0].user_id
is the same thing.
If you want check if property exist you can do it :
if(typeof $jsonObject["user"] !== 'undefined'){
//do domethings as typeof $jsonObject["user"][0]["user_id"]
}
If you want get property dinamically you can do it :
const strId = "id";
const strName = "name";
//get user_id
let user_id = $jsonObject[user][0]["user_" + strId ];
//get user_name
let user_name = $jsonObject[user][0]["user_" + strName];
but there isn't very pretty.

Printing JSON properties

I am currently trying to send a user information about a JSON object that I've recieved from an API. An example of the format is
[
{
"lang_code": "eng",
"site_language": "1",
"name": "English"
},
{
"lang_code": "afr",
"site_language": "1",
"name": "Afrikaans"
},
{
"lang_code": "ale",
"site_language": "0",
"name": "Aleut"
},
]
I want to be able to access the lang_code property of every single language and send it. I've tried to use
var languageCodes;
var languageResult = body.lang_code; //body is the result from a request.get({ ... })
for(var codes in languageResult) {
languageCodes = languageResult[codes];
}
Object.keys does nothing, as it just sends 72 numbers to me. Any thoughts?
On a side note, I also want people to be able to type "! languages [my command] eng", for example, and it sends "English" instead of just sending "1 is [object Object]".
Assuming body is the array at the top of your question, if you just want an array of all the language codes, this should suffice
var languageCodes = body.map(function(lang) {
return lang.lang_code;
});
var body = [{
"lang_code": "eng",
"site_language": "1",
"name": "English"
}, {
"lang_code": "afr",
"site_language": "1",
"name": "Afrikaans"
}, {
"lang_code": "ale",
"site_language": "0",
"name": "Aleut"
}];
var languageCodes = body.map(function(lang) {
return lang.lang_code;
});
document.getElementById('out').innerHTML = JSON.stringify(languageCodes);
<pre id="out"></pre>
I looped through your lang_codes like this:
var codes = [{"lang_code":"eng","site_language":"1","name":"English"}, {"lang_code":"afr","site_language":"1","name":"Afrikaans"},{"lang_code":"ale","site_language":"0","name":"Aleut"}];
for(var i = 0; i < codes.length; i++) {
console.log(codes[i].lang_code);
}

Print contents of JSON Object

I have an object in which I used JSON Stringify with to view its contents like so:
var testing = JSON.stringify($scope.test, null, 4);
And the object looks like this when i do console.log(testing):
{
"_id": "53e866a8a595b7041f9510c9",
"start": "2014-08-04T07:00:00.000Z",
"end": "2014-08-16T07:00:00.000Z",
"location": "Australia",
"name": "Joe's Surprise",
"__v": 1,
"array": [
{
"_id": "53ddc8c98ae4813c0420e189",
"provider": "local",
"name": "Test User",
"username": "testUser",
"email": "test#test.com",
"hashedPassword": "e5ri7OVhzNQMZpSqxnB3p2FyrpxskFE3yM8jHn5hfzZZvdd57YhhJrjFWJqBQhhyZz6y8UG68mr+rQ95admtfw==",
"salt": "PVEFtMfyJ/7TX9Do0cYMdQ==",
"__v": 2,
"attending": [
"53e866a8a595b7041f9510c9"
],
"role": "user"
},
]
}
however, I want to print out the username attribute within the array attribute of variable testing but I am unable to do so. I've tried doing a for loop like so:
for(var i = 0; i < testing.array.length; i++){
console.log(testing.array[i].username);
}
But the .length attribute is considered undefined. I've also tried simply doing console.log(testing._id) to see if that works but this returns undefined. I'm not sure what I'm doing wrong, can anyone help? Thanks!
var testing = JSON.stringify($scope.test, null, 4);
is converting $scope.test into a string (presumably so you can view in a human readible format). A string contains no arrays or properties. You want it in its original form, not in a string.
you probably want:
for(var i = 0; i < $scope.test.array.length; i++){
console.log($scope.test.array[i].username);
}

Reading JSON data for a particular ID

I have some JSON data which is in the following format:
[
{
"id": 145,
"Name": "John",
"company_name": "A",
"email": "john#gmail.com",
"country": "USA"
},
{
"id": 500,
"Name": "Mike",
"company_name": "B",
"email": "mike#gmail.com",
"country": "London"
},
{
"id": 100,
"Name": "Sally",
"company_name": "C",
"email": "sally#gmail.com",
"country": "USA"
}
]
Now, suppose I ask the user to enter an id, say 100. Then I need to display all the details for this id.
I am supposed to do this as a part of a web application,where I have to invoke an display the fields of a particular id. This would have been easy if I had a hash like implementation and could display all parameters based on the key-id.
Can anybody tell me how this can be done using such kind of data?
Thanks!
You could use something like this:
(Assuming the you have a variable data with your Json Object).
function getid(id) {
var nobj;
data.forEach(function(obj) {
if(obj.id == id)
nobj = obj;
});
return nobj
}
var neededobj = getid(100);
console.log(neededobj.Name + "\n" + neededobj.email + "\netc...");
But to get the Object you have to loop through your complete array,
until it finds the right Object
see this Fiddle
I think you are looking for Associative Array,
the simplex one would be,
var associativeArray = [];
associativeArray["one"] = "First";
associativeArray["two"] = "Second";
associativeArray["three"] = "Third";
alert(associativeArray.one);
And obviusly you can add json object in value place

Categories