How to loop through JSON object that is array of objects? - javascript

I just need to retrieve an object by its id from this JSON object (peopleData). When I do typeof peopleData, it returns object. When I try to do typeof peopleData[0] (treating this object as an array because it has brackets as the opening and closing elements) it returns undefined. How do I loop through all of the objects to find the appropriate object if this JSON object is an array that returns "undefined" when I try to get a specific element of that array? I don't know how to enumerate over or de-structure this object since it is an array.
Here are the first few lines from the JSON that I was given (I changed the values but that is irrelevant. I am mainly emphasizing the bracket at the beginning). This is the raw JSON object that I copied from its raw form on GitHub:
[{
"id": "237856238235",
"ip_address": "3423423.42.42.4",
"ssn": "123133231",
"date_of_birth": "3123123",
"address": {
"home": {
"street_number": "231231",
"street_name": "ef2ef23",
"street_suffix": "8i6rth2",
"city": "wefwdfwef"
"state": "affwefwfww",
"zip": "wefsdfbghyj"
},
"work": {
"street_number": "wefgwegwe",
"street_name": "wefwefwf",
"street_suffix": "wsfaf",
"city": "aefaef",
"state": "afaef",
"zip": "aefaef"
}
}
}, {
"id": "fwefewf",
"ip_address": "fwefwf",
"ssn": "wfwef",
"date_of_birth": "wefwef",
"address": {
"home": {
"street_number": "efwef",
I have done this before with this exact data and it worked when I just used a small function that cycles through each element of the array, but I have no idea why it is not working now.

I diagnosed my problem incorrectly. It did not have to do with the JSON data. I forgot to use await when getting the data with Axios. Thanks so much for any effort you put in to help me with this.

You can use filter by the id you want.
const data = [{
"id": "237856238235",
"ip_address": "3423423.42.42.4",
"ssn": "123133231",
"date_of_birth": "3123123",
"address": {
"home": {
"street_number": "231231",
"street_name": "ef2ef23",
"street_suffix": "8i6rth2",
"city": "wefwdfwef",
"state": "affwefwfww",
"zip": "wefsdfbghyj"
},
"work": {
"street_number": "wefgwegwe",
"street_name": "wefwefwf",
"street_suffix": "wsfaf",
"city": "aefaef",
"state": "afaef",
"zip": "aefaef"
}
}
},
{
"id": "fwefewf",
"ip_address": "fwefwf",
"ssn": "wfwef",
"date_of_birth": "wefwef",
"address": {
"home": {
"street_number": "efwef",
"street_name": "ef2ef23",
"street_suffix": "8i6rth2",
"city": "wefwdfwef",
"state": "affwefwfww",
"zip": "wefsdfbghyj"
},
"work": {
"street_number": "wefgwegwe",
"street_name": "wefwefwf",
"street_suffix": "wsfaf",
"city": "aefaef",
"state": "afaef",
"zip": "aefaef"
}
}
}]
let result = data.filter(obj => obj.id === "237856238235")
//console.log(result)
console.log(result[0])

Related

JSONPath getting Error when square brackets inside of string

kI have a problem with the library https://github.com/JSONPath-Plus/JSONPath at the latest version.
Example:
{
"firstName": "John",
"lastName": "doe",
"age": 26,
"address": {
"streetAddress": "naist street",
"city": "Nara",
"postalCode": "630-0192"
},
"phoneNumbers [1]": [
{
"type": "iPhone",
"number": "0123-4567-8888"
},
{
"type": "home",
"number": "0123-4567-8910"
}
]
}
Now i want to get "phoneNumbers [1]" with
path: $..['phoneNumbers [1]']
Here is a Demo Page for testing: https://jsonpath-plus.github.io/JSONPath/demo/
That did not work because of the square brackets inside of the String.
Do anyone know how to solve this Problem.
I have a lot of Json Objects containing strings with square brackets, so if there is a solution not only for a specific case.
Is there any option to escape characters so that the problem will be solved?
The json Object above is only a Example Code to describe the Problem.
The Problem also occurs when only using JSONPath so it is not limited to that Library.
https://jsonpath.com/
This appears to be a bug in JSONPath-Plus. The jsonpath library can handle it.
const data = JSON.parse(`{
"firstName": "John",
"lastName": "doe",
"age": 26,
"address": {
"streetAddress": "naist street",
"city": "Nara",
"postalCode": "630-0192"
},
"phoneNumbers [1]": [
{
"type": "iPhone",
"number": "0123-4567-8888"
},
{
"type": "home",
"number": "0123-4567-8910"
}
]
}`);
const result = jsonpath.query(data, "$..['phoneNumbers [1]']");
console.log(result);
<script src="https://unpkg.com/jsonpath#1.1.1/jsonpath.js"></script>
There's not much you can do about this beyond:
Changing your data structure
Changing your library
Filing a bug report
There is a workaround you can use only with jsonpath-plus
$[?(#property == "phoneNumbers [1]")]

how to GET and store specific values as a list from JSON data(URL) in javascript?

I tried several approches and none of them works. I think this is because I am using JSON returned by django DRF.
I want to create a list of IFSC using this JSON in Jquery in my HTML template itself.
This is how my api returns JSON for any queryset.
{
"count": 134,
"next": "http://127.0.0.1:8000/api/bankdetailapi/?limit=5&offset=5&q=ABHY",
"previous": null,
"results": [
{
"ifsc": "ABHY0065001",
"bank": {
"name": "ABHYUDAYA COOPERATIVE BANK LIMITED",
"id": 60
},
"branch": "RTGS-HO",
"address": "ABHYUDAYA BANK BLDG., B.NO.71, NEHRU NAGAR, KURLA (E), MUMBAI-400024",
"city": "MUMBAI",
"district": "GREATER MUMBAI",
"state": "MAHARASHTRA"
},
{
"ifsc": "ABHY0065002",
"bank": {
"name": "ABHYUDAYA COOPERATIVE BANK LIMITED",
"id": 60
},
"branch": "ABHYUDAYA NAGAR",
"address": "ABHYUDAYA EDUCATION SOCIETY, OPP. BLDG. NO. 18, ABHYUDAYA NAGAR, KALACHOWKY, MUMBAI - 400033",
"city": "MUMBAI",
"district": "GREATER MUMBAI",
"state": "MAHARASHTRA"
},
{
"ifsc": "ABHY0065003",
"bank": {
"name": "ABHYUDAYA COOPERATIVE BANK LIMITED",
"id": 60
},
"branch": "BAIL BAZAR",
"address": "KMSPM'S SCHOOL, WADIA ESTATE, BAIL BAZAR-KURLA(W), MUMBAI-400070",
"city": "MUMBAI",
"district": "GREATER MUMBAI",
"state": "MAHARASHTRA"
}
]
}
The code I tried:
$(document).ready(function(){
var value = $('#q').val()
$.getJSON("http://127.0.0.1:8000/api/bankdetailapi/?q="+ value, function(data){
var text = `IFSC: ${data.ifsc}`
})
)}
It throws error in browser console that Uncaught ReferenceError: text is not defined . I want to use this IFSC list as autocomplete suggestions.
$("#q").keyup(function(){
var value = $('#q').val()
$.getJSON("http://127.0.0.1:8000/api/bankdetailapi/?q="+ value, function(data){
var text = ['']
for (var i=0;i<data.results.length;++i){text.push(data.results[i].ifsc)}
// var text = `IFSC: ${data.results.ifsc}`
console.log(text)
By using push method and iterating on whole data i managed to get list of all IFSC values.

Not able to read below JSON using Angular 7

I was not able to read below mentioned received JSON from Rest API.
{
"details": {
"id": 21,
"gstin": "27AACCG7831Q1Z0",
"entityName": "GENX ENTERTAINMENT LIMITED",
"entityPan": "AACCG7831Q",
"entityTan": "abhishek123",
"entityCin": "null",
"entityWebsite": null,
"natureOfBusiness": null,
"constitution": "\"Public Limited Company\""
},
"addresses": [
{
"id": 22,
"buildingName": "\"Solitaire Corporate Park\"",
"location": null,
"street": null,
"buildingNo": "\"S-14\"",
"state": "bihar",
"district": "\"\"",
"city": "\"\"",
"flateNo": "\"1\"",
"pincode": "\"400093\"",
"isPrimary": false
}
]
}
I want to use above data received in JSON format into a form.
Your question is not clear, but you can pass this values to a form using this :
const formValues = JSON.parse(yourJson);
this.form.values = formValues;
See The Stakblitz Code Below
stackblit_sampleCode
Hope this helps..!

get values from JSON given by randomuser.me and loop through to append in divs

hoping to use randomuser.me in a prototype i'm putting together (html, css, jquery)
I need to use its api to access profile photos.
I've got this code puling in the JSON as they show in their documentation:
$.ajax({
url: 'https://randomuser.me/api/?results=5&gender=female',
dataType: 'json',
success: function(data) {
console.log(data);
}
});
Now I need to get the url from the picture value in the JSON and write it to the background-image css of a group of divs...I imagine by creating some kind of loop, anybody have an easy to understand way of doing this?
the JSON returned looks like this:
"results": [
{
"gender": "male",
"name": {
"title": "mr",
"first": "romain",
"last": "hoogmoed"
},
"location": {
"street": "1861 jan pieterszoon coenstraat",
"city": "maasdriel",
"state": "zeeland",
"postcode": 69217
},
"email": "romain.hoogmoed#example.com",
"login": {
"username": "lazyduck408",
"password": "jokers",
"salt": "UGtRFz4N",
"md5": "6d83a8c084731ee73eb5f9398b923183",
"sha1": "cb21097d8c430f2716538e365447910d90476f6e",
"sha256": "5a9b09c86195b8d8b01ee219d7d9794e2abb6641a2351850c49c309f1fc204a0"
},
"dob": "1983-07-14 07:29:45",
"registered": "2010-09-24 02:10:42",
"phone": "(656)-976-4980",
"cell": "(065)-247-9303",
"id": {
"name": "BSN",
"value": "04242023"
},
"picture": {
"large": "https://randomuser.me/api/portraits/men/83.jpg",
"medium": "https://randomuser.me/api/portraits/med/men/83.jpg",
"thumbnail": "https://randomuser.me/api/portraits/thumb/men/83.jpg"
},
"nat": "NL"
}
],
"info": {
"seed": "2da87e9305069f1d",
"results": 1,
"page": 1,
"version": "1.1"
}
}
If I've got right you need something like this:
$( ".myDivClass" ).each(function( index ) {
$( this ).attr("background-image", results[index].picture.medium));
});
Or if you have in results only one element of array so to do: ...results[0].picture.medium...

Setting 3rd Level Nested Attribute on a Backbone Model

I'm having trouble changing the location $id on this Backbone model.
{
"approved": null,
"caption": "This is my photo!",
"created": 1393537913,
"location": {
"_id": {
"$id": 5
},
"address1": "155 West Street",
"city": "Bangkok",
"country": "THA",
"latitude": "13.136",
"longitude": "100.2068",
"postalCode": "10330",
"region": "AP"
}
}
I've tried:
model.set({"location":{"_id":{"$id": 6}}})
But that obviously overwrites the entire location object.
model.set({"location._id":{"$id":6}})
Creates a new attribute on the model, "location._id".
So, how can I dig in to the location to change that attribute?
You can do like this :
var location = model.get('location');
location._id = { "$id": 6 };

Categories