Parse JSON Array Response - javascript

I am recieving a JSON response back from an API which isnt in the right format to be parsed.
I have tried to add the missing key at the start and it won't allow it.
[
{
"deviceId": "9092eab10f4",
"name": "temperature",
"timestamp": "2017-06-13T13:19:59.673Z",
"value": 21.5
},
{
"deviceId": "9092eab10f4",
"name": "temperature",
"timestamp": "2017-06-13T13:19:59.673Z",
"value": 21.5
}
]
I would like this to have the missing key and additional curly bracket like so:
{
"data": [
{
"deviceId": "9092eab10f4",
"name": "temperature",
"timestamp": "2017-06-13T13:19:59.673Z",
"value": 21.5
},
{
"deviceId": "9092eab10f4",
"name": "temperature",
"timestamp": "2017-06-13T13:19:59.673Z",
"value": 21.5
}
]
}

I'm not sure if the response you're getting is a string or an object.
Here's a fiddle that considers both scenarios and logs your expected output to the console.
https://jsfiddle.net/6yu9ngf5/2/
I've used JSON.parse(<string>) for the case where the response is string.
For other case I just added data key to your response.

Simple object assign?
const properResponse = Object.assign({}, {data: [response.json()]});
...assuming response is fetch, or similar with a json method which returns the response object.

Related

how can i extract axios data from string?

This is response data from server
[{"username": "harry"}][{"id": 1, "name": "playlist1", "tag": "genre"}, {"id": 2, "name": "playlist1", "tag": "genre"}, {"id": 3, "name": "playlist3", "tag": "genre"}][{"1": ["https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9", "https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af"]}, {"2": ["https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9", "https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af", "https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9", "https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af"]}, {"3": ["https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9", "https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af", "https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9", "https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af"]}]
With axios, data comes as a string in the format as above.
There are three arrays in the above string, and I want to extract each one separately and store it in a variable.
It doesn't converted to JSON. How can I get the data of username and the data of the second array? I tried to access it by index, but since it is a string format, it is accessed one by one letter
You should get response fixed as sugguested by #certainperformance and #ambianbeing, but if you can't and still want to extract data from this string response you can do it by doing something like this
const axiosResponse = `[{"username": "harry"}][{"id": 1, "name": "playlist1", "tag": "genre"}, {"id": 2, "name": "playlist1", "tag": "genre"}, {"id": 3, "name": "playlist3", "tag": "genre"}][{"1": ["https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9", "https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af"]}, {"2": ["https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9", "https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af", "https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9", "https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af"]}, {"3": ["https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9", "https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af", "https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9", "https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af"]}]`;
const result = JSON.stringify(
JSON.parse('{ "data": [' + axiosResponse.split('][').join('],[') + ']}').data[1]
);
console.log(result);
The response you have posted, is not a string. It appears to be three arrays, each containing x amount of objects.
A string can be identified, by being enclosed in either double: " " or single qoutes: ' '.
You can identify the arrays by the opening and closing square brackets: [ ].
The objects can be identified by the opening and closing curly brackets: { }.
Here is a bit more readable version of your response. I have annotated each top level array, with a comment, for easier identification.
// array 1
[
{"username": "harry"}
]
// array 2
[
{ "id": 1, "name": "playlist1", "tag": "genre" },
{ "id": 2, "name": "playlist1", "tag": "genre" },
{ "id": 3, "name": "playlist3", "tag": "genre" }
]
// array 3
[
{
"1": [
"https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9",
"https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af"
]
},
{
"2": [
"https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9",
"https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af",
"https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9",
"https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af"
]
},
{
"3": [
"https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9",
"https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af",
"https://i.scdn.co/image/ab67616d0000b273503143a281a3f30268dcd9f9",
"https://i.scdn.co/image/ab67616d0000b27369fa55f10c5293bbb985c1af"
]
}
]
The third array appears to contain an object, with a list within it. Like somebody else mentioned earlier, this seems like faulty data, and I would have a look at the source, instead of trying to parse it. That being said, it isn't impossible to loop through each list, and extract the data, but it wouldn't be the correct way of doing it.

How can I extract nested value in JSON and initialize to a JS variable

my question is above and I am trying like for 45mins to extract the value under "distance" below, but I fail at every try. I hope you guys can help me.
{
"destination_addresses": [
"XXXXXXXX 60, 13XXX Berlin, Germany"
],
"origin_addresses": [
"XXXXXXX Str. 67, 10XXX Berlin, Germany"
],
"rows": [
{
"elements": [
{
"distance": {
"text": "10.4 km",
"value": 10365
},
"duration": {
"text": "21 min",
"value": 1278
},
"status": "OK"
}
]
}
],
"status": "OK"
}
So I need the value under rows --> elements --> distance then value. I tried something like this in JavaScript:
var payload = JSON.parse(body)
console.log(payload.rows["elements"].distance.value)
Thanks! :)
Süleyman Demir
let distance = payload.rows[0].elements[0].distance.value
console.log(payload)
console.log(distance)
Please note that the data is a mix of nested arrays and objects, which are different data structures in javascript. You can access an object's property by typing its name followed by a dot and the name of the property (object_name.property_name). You can access an array's element by typing the element index in square brackets next to the array's name (array_name[element_number]).
In our case we access the property "rows" which is an array of the object "payload" - payload.rows. Then we access the element number [0] of this array by typing [0] next to the property's name - payload.rows[0]. We get another object which has the property "elements" in it - payload.rows[0].elements . This property stores another array and we access its first element again -
payload.rows[0].elements[0]. We get another object and access the property "distance" which returns finally return another object that holds the property "value" we are looking for - payload.rows[0].elements[0].distance.value
Source https://eloquentjavascript.net/04_data.html
Your question was not clear, I assume that you will have multiple rows and multiple elements. There is my solution according to what I understand.
payload.rows.forEach(x=> x.elements.forEach(y => console.log(y.distance.value)))
Try like below
var body = {
"destination_addresses": ["XXXXXXXX 60, 13XXX Berlin, Germany"],
"origin_addresses": ["XXXXXXX Str. 67, 10XXX Berlin, Germany"],
"rows": [{
"elements": [{
"distance": {
"text": "10.4 km",
"value": 10365
},
"duration": {
"text": "21 min",
"value": 1278
},
"status": "OK"
}]
}],
"status": "OK"
};
var payload = JSON.parse(JSON.stringify(body));
payload.rows.forEach(row => row.elements.forEach(elem => console.log("Distance : ", elem.distance.value)))
I don't know exactly what you want, but you can get the distance object with something like that:
const payload = {
"destination_addresses": [
"XXXXXXXX 60, 13XXX Berlin, Germany"
],
"origin_addresses": [
"XXXXXXX Str. 67, 10XXX Berlin, Germany"
],
"rows": [
{
"elements": [
{
"distance": {
"text": "10.4 km",
"value": 10365
},
"duration": {
"text": "21 min",
"value": 1278
},
"status": "OK"
}
]
}
],
"status": "OK"
}
let distance = payload.rows[0].elements.map(element => {
return {
distance: element.distance
}
});
// Map returns an array, so you can get the object using the index:
console.log(distance[0]);
// If you want only the value:
console.log(distance[0].distance.value);
If you want, you can also use Object.assign or something like that to avoid getting the value by the index.
Hope it helped!
var payload = JSON.parse(body);
console.log(payload.rows[0]["elements"][0].distance.value);

Differences with API's when trying to pull data

I am having difficulty with a pulling some data from an API for a school project using Jquery.
If I use the following coinmaketcap API I get the following response
https://api.coinmarketcap.com/v1/ticker/bitcoin/
[
{
"id": "bitcoin",
"name": "Bitcoin",
"symbol": "BTC",
"rank": "1",
"price_usd": "8854.92",
"price_btc": "1.0",
"24h_volume_usd": "6759730000.0",
"market_cap_usd": "150480289107",
"available_supply": "16993975.0",
"total_supply": "16993975.0",
"max_supply": "21000000.0",
"percent_change_1h": "-0.13",
"percent_change_24h": "0.12",
"percent_change_7d": "8.3",
"last_updated": "1524459272"
}
]
I get am able to get the symbol for Bitcoin and place it into a variable by using this code
> $.getJSON('https://api.coinmarketcap.com/v1/ticker/btc/',
> function(data){
> var symbol = (data[0].symbol)
> })
Once I have it I can place it in a div.
However when I use cryptocompare API I don't get anything back
https://min-api.cryptocompare.com/data/coin/generalinfo?fsyms=BTC,&tsym=USD
$.getJSON('https://min-api.cryptocompare.com/data/coin/generalinfo?fsyms=BTC&tsym=USD', function(data){
var symbol = (data[0].Internal)
});
This is the response -
{
"Message": "Success",
"Type": 100,
"Data": [
{
"CoinInfo": {
"Id": "1182",
"Name": "BTC",
"FullName": "Bitcoin",
"Internal": "BTC",
"ImageUrl": "/media/19633/btc.png",
"Url": "/coins/btc/overview",
"Algorithm": "SHA256",
"ProofType": "PoW",
"NetHashesPerSecond": 27483320229.3688,
"BlockNumber": 518932,
"BlockTime": 600,
"BlockReward": 12.5,
"Type": 1,
"DocumentType": "Webpagecoinp"
},
"ConversionInfo": {
"Conversion": "direct",
"ConversionSymbol": "",
"CurrencyFrom": "BTC",
"CurrencyTo": "USD",
"Market": "CCCAGG",
"Supply": 16986575,
"TotalVolume24H": 380849.0498955779,
"SubBase": "5~",
"SubsNeeded": [
"5~CCCAGG~BTC~USD"
],
"RAW": [
"5~CCCAGG~BTC~USD~4~8875.23~1524460635~0.00477012~42.152119404000004~231254719~10820.885574747872~96327075.76938197~66326.58563159907~593473019.8524572~8823.46~8917.05~8804.2~8864.31~9065~8780.91~Bitfinex~7ffe9"
]
}
}
]
}
Why is the second piece of code not working? Please help!
The second API is returning an object (in JSON format), not an array - see how the first character is { and how it has keys and values? You need to access the appropriate property to get the value you want. [0] notation indicates you're trying to access the first element of the array, but the outer object is not an array in this situation.
$.getJSON('https://min-api.cryptocompare.com/data/coin/generalinfo?fsyms=BTC&tsym=USD',
function(data){
var symbol = data.Data[0].CoinInfo.Internal;
});
In both the cases, we are getting data in different form. So, To get the 'BTC' in variable .
for 1st case -> symbol = data[0] ['symbol']
for 2nd case -> symbol = data['Data'][0]['CoinInfo']['Internal']
one is an [array of JSON] while other is an [object having key 'Data' with array value].

Removing unwanted JSON data using JAVASCRIPT

I'm new to JSON and Javascript and had to make a table in Cloudant NoSQL.
So, I collected Weather data from a Weather Company in JSON format and sent it to Cloudant, but there was some data in JSON which wasn't relevant to the table I wanted to create.
Is there a way to remove the metadata and the column name "observation" from the JSON data I received using javascript?
JSON data I have:
{
"metadata": {
"language": "en-US",
"transaction_id": "1503766402801:1454518918",
"version": "1",
"latitude": 12.83,
"longitude": 77.68,
"expire_time_gmt": 1503771300,
"status_code": 200
},
"observation": {
"key": "43295",
"class": "observation",
"expire_time_gmt": 1503771300,
"obs_id": "43295",
"obs_name": "Bangalore",
"valid_time_gmt": 1503759600,
"day_ind": "N",
"temp": 75,
"wx_icon": 29
}
}
JSON data I want
{
"_id": "2e5e0da1f82157dd6f5d381a4c9ff84e",
"_rev": "1-b7a92ae5f96b051f0add3b26a14543c2",
"key": "43295",
"class": "observation",
"expire_time_gmt": 1503771300,
"obs_id": "43295",
"obs_name": "Bangalore",
"valid_time_gmt": 1503759600,
"day_ind": "N",
"temp": 75,
"wx_icon": 29
}
Thank you.
EDIT
I'm able to remove metadata using "delete data.metadata;", where data contains the JSON, but I still can't remove the "observation" word and the curly braces in the end.
Assuming your JSON is parsed, you can just assign all keys from all nested objects to a new object.
var myData = {
"metadata": {
"language": "en-US",
"transaction_id": "1503766402801:1454518918",
"version": "1",
"latitude": 12.83,
"longitude": 77.68,
"expire_time_gmt": 1503771300,
"status_code": 200
},
"observation": {
"key": "43295",
"class": "observation",
"expire_time_gmt": 1503771300,
"obs_id": "43295",
"obs_name": "Bangalore",
"valid_time_gmt": 1503759600,
"day_ind": "N",
"temp": 75,
"wx_icon": 29
}
}
myData = Object.keys(myData)
.reduce((res, key) => Object.assign(res, myData[key]), {});
console.log(myData);
There are some extra keys in your result. Not sure where those are coming from.
If there are some extra properties to delete, you can use delete to get rid of those.
["latitude", "longitude"].forEach(k => delete myData[k]);
Or perhaps I misunderstood. I though you wanted a consolidation. If you only wanted the observation object, then just assign it to the original variable.
myData = myData.observation;
And add whatever other properties you'd like.
You can create a new json object before sending. Using lodash should be an easy solution in extending
// Assume result has your json data
var wantedJson = _.extend({}, result.observation, result.metadata);
If you are not bothered about the order of the elements, this is the simplest way:
var result = {
"metadata": {
"language": "en-US",
"transaction_id": "1503766402801:1454518918",
"version": "1",
"latitude": 12.83,
"longitude": 77.68,
"expire_time_gmt": 1503771300,
"status_code": 200
},
"observation": {
"key": "43295",
"class": "observation",
"expire_time_gmt": 1503771300,
"obs_id": "43295",
"obs_name": "Bangalore",
"valid_time_gmt": 1503759600,
"day_ind": "N",
"temp": 75,
"wx_icon": 29
}
}
var myjson = result.observation;
myjson._id = "2e5e0da1f82157dd6f5d381a4c9ff84e",
myjson._rev = "1-b7a92ae5f96b051f0add3b26a14543c2";
console.log(myjson);

Accessing json elements gives undefined error

I have the following JSON:
{
"list": {
"q": "raw",
"sr": "28",
"ds": "Standard Reference",
"start": 0,
"end": 1,
"total": 1391,
"group": "",
"sort": "n",
"item": [
{
"offset": 0,
"group": "Poultry Products",
"name": "Chicken, broilers or fryers, dark meat, thigh, meat only, raw",
"ndbno": "05096",
"ds": "SR"
}
]
}
}
But when I try to access elements in this json i keep getting undefined error... I already checked if the JSON is valid and yes the json is valid!
Maybe I am accesing the JSON wrong? The JSON is stored in a variable called result. This is how I tried so far:
console.log(result.list.ds);
I also tried:
console.log(result["0"].list.ds);
but both solutions give me the following error:
Uncaught TypeError: Cannot read property 'ds' of undefined
Why is this happening? Any tips or suggestions are welcome!
Is your JSON stored in your variable as a string? Try:
console.log(JSON.parse(result).list.ds)
The reason I ask is that the text Uncaught TypeError: Cannot read property 'ds' of undefined tells me that your result variable does not have a list property, which your JSON clearly would if it were an object, but it most assuredly would not if you had accidentally forgotten to parse your JSON string.
Your JSON is valid and if you are accessing the ds property inside list object. Your syntax console.log(result.list.ds); is correct.
But, If you are trying to access the ds property inside the item array then you have to iterate the array to get the ds property.
DEMO
var result = {
"list": {
"q": "raw",
"sr": "28",
"ds": "Standard Reference",
"start": 0,
"end": 1,
"total": 1391,
"group": "",
"sort": "n",
"item": [{
"offset": 0,
"group": "Poultry Products",
"name": "Chicken, broilers or fryers, dark meat, thigh, meat only, raw",
"ndbno": "05096",
"ds": "SR"
}]
}
};
var res = result.list.item.map(function(elem) {
return elem.ds;
})
console.log(res);

Categories