I am trying to parse the following JSON payload:
{
"results":[
[
298.648132,
280.68692,
356.54184,
388.085541,
183.491806,
-484.676086,
-468.069916,
-446.741699
],
[
299.641846,
285.005798,
358.563812,
389.283997,
212.144806,
-485.533844,
-469.071533,
-447.885406
],
[
302.24469,
291.76059,
362.658936,
392.376129,
217.732513,
-484.816711,
-468.566711,
-447.615082
],
[
303.058899,
297.929199,
365.46994,
393.894928,
213.591797,
-486.055756,
-469.872986,
-449.343323
],
[
304.604095,
304.826233,
369.112122,
396.274597,
206.882492,
-486.385498,
-470.249512,
-450.089935
],
[
305.541901,
306.31842,
370.016907,
396.985413,
200.299408,
-486.345032,
-470.176208,
-450.01059
],
[
305.137024,
306.015381,
369.381042,
396.26059,
196.422821,
-487.490143,
-471.321533,
-451.191711
],
[
306.182373,
307.574707,
370.42627,
397.127747,
206.874603,
-487.188477,
-471.038483,
-450.869781
],
[
307.108887,
309.183777,
371.413666,
397.890198,
234.509079,
-486.957367,
-470.937103,
-450.646393
],
[
308.208923,
310.277588,
372.322968,
398.777618,
244.5168,
-486.2995,
-470.352631,
-449.89325
],
[
308.676208,
310.526123,
372.360626,
398.743317,
250.976288,
-486.666687,
-470.868408,
-450.324463
],
[
308.910583,
310.629242,
372.255676,
398.59491,
252.538498,
-487.001068,
-471.305817,
-450.616699
]
],
"columns":[
"5bb6a5d20ff4c313aab7241c.value.value",
"5bb6a5d30ff4c313aab72421.value.value",
"5bb6a5d30ff4c313aab72425.value.value",
"5bb6a5d30ff4c313aab72426.value.value",
"5bb6a5d30ff4c313091fe079.value.value",
"5bb6a5d30ff4c313091fe07b.value.value",
"5bb6a5d30ff4c313091fe07c.value.value",
"5bb6a5d40ff4c313091fe07f.value.value"
]
}
I am only interested in the "results" section. I will end up plotting these values.
I am proficient in C++, but new to JavaScript.
I've found plenty of examples with typical JSON strings, but I haven't found anything that works for this yet.
Thanks for the help.
Try the JSON.parse() function:
const payload = // your json payload
const json = JSON.parse(payload);
const results = json.results;
If you can copy-paste your json to your JS code directly then try
const payload = {"results": [ ... } // your json
const results = payload.results;
const payload ={"results":[[298.648132,280.68692,356.54184,388.085541,183.491806,-484.676086,-468.069916,-446.741699],
[299.641846,285.005798,358.563812,389.283997,212.144806,-485.533844,-469.071533,-447.885406],
[302.24469,291.76059,362.658936,392.376129,217.732513,-484.816711,-468.566711,-447.615082],
[303.058899,297.929199,365.46994,393.894928,213.591797,-486.055756,-469.872986,-449.343323],
[304.604095,304.826233,369.112122,396.274597,206.882492,-486.385498,-470.249512,-450.089935],
[305.541901,306.31842,370.016907,396.985413,200.299408,-486.345032,-470.176208,-450.01059],
[305.137024,306.015381,369.381042,396.26059,196.422821,-487.490143,-471.321533,-451.191711],
[306.182373,307.574707,370.42627,397.127747,206.874603,-487.188477,-471.038483,-450.869781],
[307.108887,309.183777,371.413666,397.890198,234.509079,-486.957367,-470.937103,-450.646393],
[308.208923,310.277588,372.322968,398.777618,244.5168,-486.2995,-470.352631,-449.89325],
[308.676208,310.526123,372.360626,398.743317,250.976288,-486.666687,-470.868408,-450.324463],
[308.910583,310.629242,372.255676,398.59491,252.538498,-487.001068,-471.305817,-450.616699]],
"columns":["5bb6a5d20ff4c313aab7241c.value.value","5bb6a5d30ff4c313aab72421.value.value",
"5bb6a5d30ff4c313aab72425.value.value","5bb6a5d30ff4c313aab72426.value.value",
"5bb6a5d30ff4c313091fe079.value.value","5bb6a5d30ff4c313091fe07b.value.value",
"5bb6a5d30ff4c313091fe07c.value.value","5bb6a5d40ff4c313091fe07f.value.value"]}
const results = payload.results;
console.log(results);
Related
I am looking for a way to loop over an array of objects and make a new array from the contents of an object property. See the array below. I want to make an array called topics (with no duplicates) from each of the topic properties on each object.
const data = [
{
topics [
"tutorial",
"JS",
"Video"
],
...
},
{
topics [
"tutorial",
"CSS",
"Testing"
],
...
},
{
topics [
"HTML",
"JS",
"Music"
],
...
}
]
I was thinking of:
let topics = []
data.forEach((item) => {
topics.push(item.topics, ...topics)
})
You need to use flatMap method to flat the topics together, and with new Set(Array) you will get the unique values.
const data = [
{
topics: [
"tutorial",
"JS",
"Video"
],
},
{
topics: [
"tutorial",
"CSS",
"Testing"
],
},
{
topics: [
"HTML",
"JS",
"Music"
],
}
]
const topics = new Set(data.flatMap(item => item.topics))
console.log(Array.from(topics))
Given an array of data objects
const data = [{
"id": "CT20",
"type": "a11y-unknown",
"urls": ["https://www.example.com/test/"]
},
{
"id": "BC192",
"type": "a11y-true",
"urls": [
"https://www.example.com/something/",
"https://www.example.com/another-thing/"
]
}
]
I'm trying to convert the objects to a CSV file that can be imported to Excel so that it shows as:
id | type | urls
CT20 | a11y-unknown| https://www.example.com/test/
I'm using the following to get the keys:
const keys = Object.keys(data[0]);
then map over the data like so:
const commaSeparatedString = [keys.join(","),data.map(row => keys.map(key => row[key]).join(",")).join("\n")].join("\n");
However, this returns the following:
'id,type,urls\nCT20,a11y-unknown,https://www.example.com/test/\nBC192,a11y-true,https://www.example.com/something/,https://www.example.com/another-thing/'
When imported to Excel as a CSV file, and delimited with \, it appears like this:
How can I correctly map the objects so that they are delimited and line break after each set of urls?
const data = [{
"id": "CT20",
"type": "a11y-unknown",
"urls": ["https://www.example.com/test/"]
},
{
"id": "BC192",
"type": "a11y-true",
"urls": [
"https://www.example.com/something/",
"https://www.example.com/another-thing/"
]
}
]
const keys = Object.keys(data[0]);
const commaSeparatedString = [keys.join(","),data.map(row => keys.map(key => row[key]).join(",")).join("\n")].join("\n");
console.log(commaSeparatedString)
You need to have fixed number of columns. So either JSON.stringify the urls array, or designate columns such as url1, url2, url3...
EDIT: naturally if you don't escape commas by enclosing them in quotes, it will break the CSV. Genrally speaking you should use a library for parsing CSV such as papaparse.
const data = [{
"id": "CT20",
"type": "a11y-unknown",
"urls": ["https://www.example.com/test/"]
},
{
"id": "BC192",
"type": "a11y-true",
"urls": [
"https://www.example.com/something/",
"https://www.example.com/another-thing/"
]
}
]
var keys = Object.keys(data[0]);
var arr = [keys, ...data.map(row => keys.map(key => {
return typeof row[key] === "string" ? row[key] : JSON.stringify(row[key])
}))];
// don't!
// .join(",")).join("\n")].join("\n");
// instead
var csv = Papa.unparse(arr);
console.log(csv)
<script src="https://cdnjs.cloudflare.com/ajax/libs/PapaParse/5.1.0/papaparse.min.js"></script>
As a general rule, the csv must be delimited with the same delimiter used when importing it, also for reliability all the fields should be included into quotes, so since in your case the delimiter is \, your attempt can be rewritten as below:
const data = [{
"id": "CT20",
"type": "a11y-unknown",
"urls": ["https://www.example.com/test/"]
},
{
"id": "BC192",
"type": "a11y-true",
"urls": [
"https://www.example.com/something/",
"https://www.example.com/another-thing/"
]
}
]
const keys = Object.keys(data[0]);
const commaSeparatedString = [keys.join("\\"),data.map(row => keys.map(key => `"${[row[key]].flat().join()}"`).join("\\")).join("\n")].join("\n");
console.log(commaSeparatedString)
I am trying to gain access within the last array of the json file and return the value from the "data" array of the json file and put it into the choiceSelection array. However, on my local host, it returns an undefined value and the images would not load. Can anyone help me out? I apologise if I haven't clearly explained my problem/logic and so please ask me for more details, if you're not sure. Thanks!
javascript code
$.getJSON('data.json', function(json) {
if(json[2].data){
for (i = 0; i < json[3].data.length; i++) {
choiceSelection[i] = new Array;
choiceSelection[i][0] = json[2].data[i].question;
choiceSelection[i][1] = json[2].data[i].correctChoice;
choiceSelection[i][2] = json[2].data[i].choice1;
choiceSelection[i][3] = json[2].data[i].choice2;
}
// choiceSelection.length = choiceSelection.length;
displayQuestion();
console.log(json[2]);
}
})
json file
[
{
"name": "match numbers 1",
"template": "matching",
"data": [
[
"six",
"Images/Number6.jpg"
],
[
"eight",
"Images/Number8.jpg"
],
[
"nine",
"Images/Number9.jpg"
]
]
},
{
"name": "order numbers 1",
"template": "ordering",
"data": [
[
"Images/Number6.jpg"
],
[
"Images/Number8.jpg"
],
[
"Images/Number9.jpg"
]
]
},
{
"name": "animal",
"template": "picture game",
"data": [
{
"question": "Where is the cat?",
"correctChoice": "Images/5cats.jpg",
"choice1": "Images/squirrel.png",
"choice2": "Images/beagle.png"
},
{
"question": "Where is the cat?",
"correctChoice": "Images/5cats.jpg",
"choice1": "Images/squirrel.png",
"choice2": "Images/beagle.png"
}
]
}
]
Edit 1: change json[i] to json[2].data. Still undefined
Edit 2: changed json[2].data. to json[2].data[i] and used json[3].data.length in the for statement. It works perfectly now. Thank you everyone for the help!:)
You could take the hassle out of your code and use some ES6 destructuring to get at your data more easily.
const json = '[{"name":"match numbers 1","template":"matching","data":[["six","Images/Number6.jpg"],["eight","Images/Number8.jpg"],["nine","Images/Number9.jpg"]]},{"name":"order numbers 1","template":"ordering","data":[["Images/Number6.jpg"],["Images/Number8.jpg"],["Images/Number9.jpg"]]},{"name":"animal","template":"picture game","data":[{"question":"Where is the cat?","correctChoice":"Images/5cats.jpg","choice1":"Images/squirrel.png","choice2":"Images/beagle.png"},{"question":"Where is the cat?","correctChoice":"Images/5cats.jpg","choice1":"Images/squirrel.png","choice2":"Images/beagle.png"}]}]'
function getJSON(endpoint, callback) {
setTimeout(() => callback(JSON.parse(json)), 1000);
}
// grab the third object from the response data
getJSON('data.json', function([ ,,obj ]) {
// grab the data array from that object but relabel it
// `choiceSelection
const { data: choiceSelection } = obj;
// then use the object property keys to get access
// to the data instead of indexes. Much easier.
console.log(choiceSelection[0].question);
console.log(choiceSelection[1].question);
});
I have layout builder in React to keep data structure and text I use ImmutableJS objects.
Such structure with attributes as text or css styles is saved into database as JSON.
To make it JSON I using json-immutable library: serialize, deserialize functions.
After save in database I provide configuration for react components as javascript variables. For example my backend generate js file with variables or small part is printing directly in html code using script tag.
Data are JSON or decoded javascript.
The biggest problem I have with save special chars.
For example if someone set ' single quote in some attribute it is saved directly.
But when I print it in html code as
var myConfig = '{anyjson}';
when inside JSON is single quote parser throw error. The same with double quotes, & (ampersant) or any chars used in html code like <,/>
Single quote I replace to \' when I print it in html code.
But I think does exists any way to save keep all data in JSON and still they will easy to decode by deserialize function to parse JSON to ImmutableJS objects.
Code example
https://jsfiddle.net/jaroapp/2yzud6ua/2/
var structure = {
"__iterable":"Map",
"data":[
[
"entityMap",
{
"__iterable":"Map",
"data":[
[
"html_el_qb7tyhi",
{
"__iterable":"Map",
"data":[
[
"imported",
false
],
[
"path",
"html_el_qb7tyhi"
],
[
"componentData",
{
"__iterable":"Map",
"data":[
]
}
],
[
"draftjsObject",
{
"__iterable":"OrderedMap",
"data":[
]
}
],
[
"draftjs",
true
],
[
"data",
{
"__iterable":"OrderedMap",
"data":[
[
"text",
"B&B is the best company. It's my hope for new markets."
]
]
}
],
[
"chunk",
null
],
[
"style",
{
"__iterable":"OrderedMap",
"data":[
[
"background-image",
"url(\"/path/to/image.jpg\")"
]
]
}
],
[
"attr",
{
"__iterable":"OrderedMap",
"data":[
]
}
],
[
"runEditor",
false
],
[
"entityMap",
{
"__iterable":"OrderedMap",
"data":[
]
}
],
[
"type",
"div"
],
[
"key",
"html_el_qb7tyhi"
]
]
}
],
[
"html_el_2dgupn7",
{
"__iterable":"Map",
"data":[
[
"imported",
false
],
[
"path",
"html_el_2dgupn7"
],
[
"componentData",
{
"__iterable":"Map",
"data":[
]
}
],
[
"draftjsObject",
{
"entityMap":{
},
"blocks":[
{
"key":"3ia22",
"text":"Text saved with html inside",
"type":"unstyled",
"depth":0,
"inlineStyleRanges":[
],
"entityRanges":[
],
"data":{
}
}
]
}
],
[
"draftjs",
true
],
[
"data",
{
"__iterable":"OrderedMap",
"data":[
[
"text",
null
],
[
"html",
"<p class=\"md-block-unstyled\">Text saved with html inside</p>"
]
]
}
],
[
"chunk",
null
],
[
"style",
{
"__iterable":"OrderedMap",
"data":[
]
}
],
[
"attr",
{
"__iterable":"OrderedMap",
"data":[
]
}
],
[
"runEditor",
false
],
[
"entityMap",
{
"__iterable":"OrderedMap",
"data":[
]
}
],
[
"type",
"div"
],
[
"key",
"html_el_2dgupn7"
]
]
}
]
]
}
],
[
"containersMap",
{
"__iterable":"Map",
"data":[
]
}
],
[
"componentsMap",
{
"__iterable":"Map",
"data":[
[
"entityMap",
{
"__iterable":"OrderedMap",
"data":[
]
}
]
]
}
]
]
};
Such structure I set as parameter into ReactJS component.
If I set it as JSON and wrap in quotes then the browser throws an error. If I set it as JavaScript object into the React component I can't make ImmutableJS from this one, because this structure is read by this
https://www.npmjs.com/package/json-immutable library (I use the same to make JSON from Immutable JS to save it in database);
Thanks in advance for any hints.
I solved this problem. Short description, maybe will helpful for someone.
I get file with deserialize function form json-immutable package. And I modified function deserialize to
export function deserialize(json){
var options = arguments.length > 1 && arguments[1] !== undefined ? arguments[1] : {};
if(typeof json==='string'){
return JSON.parse(json, function(key, value, options){
return revive(key, value, options);
});
}else{
return JSON.parse(JSON.stringify(json), function(key, value, options){
return revive(key, value, options);
});
}
}
Function in package use JSON.parse for param. Maybe it's not the most elegant solution but I don't have time to find way to don't "re-json" object. Standard Object.keys and map return origin object.
Hi My Json Looks like below and i want to parse it to bind the data to array. Please provide me how i can parse it?
[
{
"ImgUrl": "http://www.cowboysalamocityharley.com/used_bikes/DSC_7815.JPG",
"CarouselImages": [
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7816.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7817.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7818.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7819.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7820.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7821.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7822.JPG"
],
"VehicleId": 1
},
{
"ImgUrl": "http://www.cowboysalamocityharley.com/used_bikes/DSC_7816.JPG",
"CarouselImages": [
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7816.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7817.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7818.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7819.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7820.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7821.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7822.JPG"
],
"VehicleId": 2
},
{
"ImgUrl": "http://www.cowboysalamocityharley.com/used_bikes/DSC_7817.JPG",
"CarouselImages": [
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7816.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7817.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7818.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7819.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7820.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7821.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7822.JPG"
],
"VehicleId": 3
},
{
"ImgUrl": "http://www.cowboysalamocityharley.com/used_bikes/DSC_7818.JPG",
"CarouselImages": [
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7816.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7817.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7818.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7819.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7820.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7821.JPG",
"http://www.cowboysalamocityharley.com/used_bikes/th_DSC_7822.JPG"
],
"VehicleId": 4
}
]
is there any way i can parse it using an inbuilt library or shall i need to loop through?
try this
var json = eval("(" + result + ")");
Try this:
var arr = JSON.parse(data);