javascript Json parse error Doubleqoutes - javascript

i am getting an error when i parse a json string in javascript.
"Uncaught SyntaxError: Unexpected token Z" I know its for the double qoutes in the "Source" tag, but how do i parse this?
<script type="text/javascript">
var data = '[ { "Outcome": "Success", "Message": null, "Identity": "Request", "Delay": 0.115825, "BaseCurrency": "EUR", "QuoteCurrency": "USD", "Symbol": "EURUSD", "Date": "10/07/2015", "Time": "2:46:32 PM", "QuoteType": "Spot", "Bid": 1.12394, "Mid": 1.12397, "Ask": 1.124, "Spread": 0.00006, "Text": "1 European Union euro = 1.12397 United States dollars", "Source": "SIX Financial Information, Buyer = \"ZKB Zuercher Kantonalbank, Devisen\", Seller = \"ZKB Zuercher Kantonalbank, Devisen\"" }, { "Outcome": "Success", "Message": null, "Identity": null, "Delay": 0, "BaseCurrency": "GBP", "QuoteCurrency": "USD", "Symbol": "GBPUSD", "Date": "10/07/2015", "Time": "2:46:32 PM", "QuoteType": "Spot", "Bid": 1.5293, "Mid": 1.5295, "Ask": 1.5297, "Spread": 0.0004, "Text": "1 British pound sterling = 1.5295 United States dollars", "Source": "SIX Financial Information, Buyer = \"UBS Investment Bank\", Seller = \"UBS Investment Bank\"" } ]';
var obj = JSON.parse(data);
for(var key in obj){
console.log(obj[key].Symbol);
}
</script>
I could use replace methods but thats not a clean solution i think.

You need to escape your backslashes as well. Instead of \", type \\".

Not sure why you're using JSON here. Just do this:
<script type="text/javascript">
var obj = [ { "Outcome": "Success", "Message": null, "Identity": "Request", "Delay": 0.115825, "BaseCurrency": "EUR", "QuoteCurrency": "USD", "Symbol": "EURUSD", "Date": "10/07/2015", "Time": "2:46:32 PM", "QuoteType": "Spot", "Bid": 1.12394, "Mid": 1.12397, "Ask": 1.124, "Spread": 0.00006, "Text": "1 European Union euro = 1.12397 United States dollars", "Source": "SIX Financial Information, Buyer = \"ZKB Zuercher Kantonalbank, Devisen\", Seller = \"ZKB Zuercher Kantonalbank, Devisen\"" }, { "Outcome": "Success", "Message": null, "Identity": null, "Delay": 0, "BaseCurrency": "GBP", "QuoteCurrency": "USD", "Symbol": "GBPUSD", "Date": "10/07/2015", "Time": "2:46:32 PM", "QuoteType": "Spot", "Bid": 1.5293, "Mid": 1.5295, "Ask": 1.5297, "Spread": 0.0004, "Text": "1 British pound sterling = 1.5295 United States dollars", "Source": "SIX Financial Information, Buyer = \"UBS Investment Bank\", Seller = \"UBS Investment Bank\"" } ];
for(var key in obj){
console.log(obj[key].Symbol);
}
</script>

Related

Fetch and parse multiple arrays from .json file

I'm making a collection of all the movies I've watched and I keep all my data in movies.json. In movies.json there are multiple arrays, the first one being "MarvelMovies" with 2 movies in.
Next is "ComedyMovies" with also 4 movies.
I can console.log all the arrays, but I haven't figured out how to console.log each array (console.log the MarvelMovies array and ComedyMovies separately).
movies.json:
{
"MarvelMovies": [{
"Title": "The Avengers",
"Year": "2012",
"Poster": "https://m.media-amazon.com/images/M/MV5BNDYxNjQyMjAtNTdiOS00NGYwLWFmNTAtNThmYjU5ZGI2YTI1XkEyXkFqcGdeQXVyMTMxODk2OTU#._V1_SX300.jpg",
"Ratings": [{
"Source": "Internet Movie Database",
"Value": "8.0/10"
}, {
"Source": "Rotten Tomatoes",
"Value": "91%"
}, {
"Source": "Metacritic",
"Value": "69/100"
}],
"Metascore": "69"
}, {
"Title": "Avengers: Age of Ultron",
"Year": "2015",
"Rated": "PG-13",
"Released": "01 May 2015",
"Runtime": "141 min",
"Genre": "Action, Adventure, Sci-Fi",
"Director": "Joss Whedon",
"Writer": "Joss Whedon, Stan Lee (based on the Marvel comics by), Jack Kirby (based on the Marvel comics by), Joe Simon (character created by: Captain America), Jack Kirby (character created by: Captain America), Jim Starlin (character created by: Thanos)",
"Actors": "Robert Downey Jr., Chris Hemsworth, Mark Ruffalo, Chris Evans",
"Plot": "When Tony Stark and Bruce Banner try to jump-start a dormant peacekeeping program called Ultron, things go horribly wrong and it's up to Earth's mightiest heroes to stop the villainous Ultron from enacting his terrible plan.",
"Language": "English, Korean",
"Country": "USA",
"Awards": "8 wins & 49 nominations.",
"Poster": "https://m.media-amazon.com/images/M/MV5BMTM4OGJmNWMtOTM4Ni00NTE3LTg3MDItZmQxYjc4N2JhNmUxXkEyXkFqcGdeQXVyNTgzMDMzMTg#._V1_SX300.jpg",
"Ratings": [{
"Source": "Internet Movie Database",
"Value": "7.3/10"
}, {
"Source": "Rotten Tomatoes",
"Value": "75%"
}, {
"Source": "Metacritic",
"Value": "66/100"
}],
"Metascore": "66",
"imdbRating": "7.3",
"imdbVotes": "759,059",
"imdbID": "tt2395427",
"Type": "movie",
"DVD": "08 Sep 2015",
"BoxOffice": "$459,005,868",
"Production": "Marvel Studios",
"Website": "N/A",
"Response": "True"
}
],
"ComedyMovies": [{
"Title": "The Avengers",
"Year": "2012",
"Poster": "https://m.media-amazon.com/images/M/MV5BNDYxNjQyMjAtNTdiOS00NGYwLWFmNTAtNThmYjU5ZGI2YTI1XkEyXkFqcGdeQXVyMTMxODk2OTU#._V1_SX300.jpg",
"Ratings": [{
"Source": "Internet Movie Database",
"Value": "8.0/10"
}, {
"Source": "Rotten Tomatoes",
"Value": "91%"
}, {
"Source": "Metacritic",
"Value": "69/100"
}],
"Metascore": "69"
}, {
"Title": "Avengers: Age of Ultron",
"Year": "2015",
"Rated": "PG-13",
"Released": "01 May 2015",
"Runtime": "141 min",
"Genre": "Action, Adventure, Sci-Fi",
"Director": "Joss Whedon",
"Writer": "Joss Whedon, Stan Lee (based on the Marvel comics by), Jack Kirby (based on the Marvel comics by), Joe Simon (character created by: Captain America), Jack Kirby (character created by: Captain America), Jim Starlin (character created by: Thanos)",
"Actors": "Robert Downey Jr., Chris Hemsworth, Mark Ruffalo, Chris Evans",
"Plot": "When Tony Stark and Bruce Banner try to jump-start a dormant peacekeeping program called Ultron, things go horribly wrong and it's up to Earth's mightiest heroes to stop the villainous Ultron from enacting his terrible plan.",
"Language": "English, Korean",
"Country": "USA",
"Awards": "8 wins & 49 nominations.",
"Poster": "https://m.media-amazon.com/images/M/MV5BMTM4OGJmNWMtOTM4Ni00NTE3LTg3MDItZmQxYjc4N2JhNmUxXkEyXkFqcGdeQXVyNTgzMDMzMTg#._V1_SX300.jpg",
"Ratings": [{
"Source": "Internet Movie Database",
"Value": "7.3/10"
}, {
"Source": "Rotten Tomatoes",
"Value": "75%"
}, {
"Source": "Metacritic",
"Value": "66/100"
}],
"Metascore": "66",
"imdbRating": "7.3",
"imdbVotes": "759,059",
"imdbID": "tt2395427",
"Type": "movie",
"DVD": "08 Sep 2015",
"BoxOffice": "$459,005,868",
"Production": "Marvel Studios",
"Website": "N/A",
"Response": "True"
}
]
}
my js fetch code:
//DOM element
let movieSlider = document.querySelector(".mainSlider") //Grid til film
let movieTitle = document.querySelector(".mainSlider__title"); //genre titel
fetch('./media/json/movies.json')
.then(response => response.json())
.then((movies) => {
console.log(movies)
// console.log(response);
// });
// .then(movie => {
for (let i = 0; i < movies.length; i++) {
const element = movies[i];
movieSlider.innerHTML += `
<div class="mainSlider__item" style='background:url("${element.Poster}"); background-size:cover;'>
<div class="mainSlider__item-playButton">
<div class="mainSlider__item-title">${element.Title}</div>
<div class="mainSlider__item-info">${element.Year}</div>
<div class="mainSlider__item-desc">${element.Runtime}</div>
</div>
</div>
`
}
});
If you don't know the property names and also you don't need them. (They seem like categories). You can use Object.values and Array.flat methods to retrieve an array that contains just movies like below :
const json = `your json`
const movies = Object.values(json).flat();
console.log(movies);
const json = `your json`
const movies = Object.values(json).flat();
console.log(movies);

nodejs axios JSON with Objects under the same name

So, My JS Looks Like This
#!/usr/bin/env node
var axios = require("axios");
var chalk = require("chalk");
var columnify = require('columnify')
var lineBreak = '-----------------------'
const info_url = `https://api.jikan.moe/v3/anime/22663`
axios.get(info_url, { headers: { Accept: "application/json" } }).then(anime => {
// console.log(anime.data.title)
var data = {
"Title (Romaji):": anime.data.title,
"Title (English):": anime.data.title_english,
"Title (Japanese):": anime.data.title_japanese,
"MAL ID": anime.data.mal_id,
"Title Synonyms:": anime.data.title_synonyms,
"Type": anime.data.type,
"Source:": anime.data.source,
"Status:": anime.data.status,
"Duration:": anime.data.duration,
"Rating:": anime.data.rating,
"Score:": anime.data.score,
"Rank": anime.data.rank,
"Popularity:": anime.data.popularity,
"Members:": anime.data.members,
"Favorites": anime.data.favorites,
"Premiered:": anime.data.premiered,
"Broadcast:": anime.data.broadcast,
"Genres:": anime.data.genres,
"\n": "\n",
}
console.log(columnify(data, {columns: [' ', ' ']}))
console.log(chalk.green("Synopsis:"))
console.log(anime.data.synopsis)
console.log(`\n`)
})
So Basically I'm Showing JSON Objects in the CLI, First Off here is the json file i'm currently using for this example
{
"request_hash": "request:anime:06c1f9aadcb4e3286fa86947ba8451bfc8c6d3a7",
"request_cached": true,
"request_cache_expiry": 73254,
"mal_id": 22663,
"url": "https://myanimelist.net/anime/22663/Seiken_Tsukai_no_World_Break",
"image_url": "https://cdn.myanimelist.net/images/anime/7/71769.jpg",
"trailer_url": "https://www.youtube.com/embed/zGXx54r4yWU?enablejsapi=1&wmode=opaque&autoplay=1",
"title": "Seiken Tsukai no World Break",
"title_english": "World Break: Aria of Curse for a Holy Swordsman",
"title_japanese": "聖剣使いの禁呪詠唱〈ワールドブレイク〉",
"title_synonyms": [
"Seiken Tsukai no Kinshuu Eishou",
"Warubure"
],
"type": "TV",
"source": "Light novel",
"episodes": 12,
"status": "Finished Airing",
"airing": false,
"aired": {
"from": "2015-01-12T00:00:00+00:00",
"to": "2015-03-30T00:00:00+00:00",
"prop": {
"from": {
"day": 12,
"month": 1,
"year": 2015
},
"to": {
"day": 30,
"month": 3,
"year": 2015
}
},
"string": "Jan 12, 2015 to Mar 30, 2015"
},
"duration": "24 min per ep",
"rating": "R - 17+ (violence & profanity)",
"score": 6.93,
"scored_by": 117100,
"rank": 3889,
"popularity": 602,
"members": 228214,
"favorites": 813,
"synopsis": "Seiken Tsukai no World Break takes place at Akane Private Academy where students who possess memories of their previous lives are being trained to use Ancestral Arts so that they can serve as defenders against monsters, called Metaphysicals, who randomly attack. Known as saviors, the students are broken up into two categories: the kurogane who are able to use their prana to summon offensive weapons and the kuroma who are able to use magic. The story begins six months prior to the major climax of the series during the opening ceremonies on the first day of the school year. After the ceremony is over, the main character, Moroha Haimura, meets a girl named Satsuki Ranjou who reveals that she was Moroha's little sister in a past life where Moroha was a heroic prince capable of slaying entire armies with his sword skills. Soon afterwards he meets another girl, Shizuno Urushibara, who eventually reveals that she also knew Moroha in an entirely different past life where he was a dark lord capable of using destructive magic but saved her from a life of slavery. Can those whose minds live in both the present and the past truly reach a bright future? Delve into the complex world of Seiken Tsukai no World Break to find out!",
"background": null,
"premiered": "Winter 2015",
"broadcast": "Mondays at 01:05 (JST)",
"related": {
"Adaptation": [
{
"mal_id": 57101,
"type": "manga",
"name": "Seiken Tsukai no World Break",
"url": "https://myanimelist.net/manga/57101/Seiken_Tsukai_no_World_Break"
}
]
},
"producers": [
{
"mal_id": 64,
"type": "anime",
"name": "Sotsu",
"url": "https://myanimelist.net/anime/producer/64/Sotsu"
}
],
"licensors": [
{
"mal_id": 102,
"type": "anime",
"name": "Funimation",
"url": "https://myanimelist.net/anime/producer/102/Funimation"
}
],
"studios": [
{
"mal_id": 51,
"type": "anime",
"name": "Diomedea",
"url": "https://myanimelist.net/anime/producer/51/Diomedea"
}
],
"genres": [
{
"mal_id": 1,
"type": "anime",
"name": "Action",
"url": "https://myanimelist.net/anime/genre/1/Action"
},
{
"mal_id": 10,
"type": "anime",
"name": "Fantasy",
"url": "https://myanimelist.net/anime/genre/10/Fantasy"
},
{
"mal_id": 35,
"type": "anime",
"name": "Harem",
"url": "https://myanimelist.net/anime/genre/35/Harem"
},
{
"mal_id": 22,
"type": "anime",
"name": "Romance",
"url": "https://myanimelist.net/anime/genre/22/Romance"
},
{
"mal_id": 23,
"type": "anime",
"name": "School",
"url": "https://myanimelist.net/anime/genre/23/School"
},
{
"mal_id": 37,
"type": "anime",
"name": "Supernatural",
"url": "https://myanimelist.net/anime/genre/37/Supernatural"
}
],
"opening_themes": [
"\"Hi no Ito Rinne no Gemini (緋ノ糸輪廻ノGEMINI)\" by petit milady (eps 2-11)"
],
"ending_themes": [
"#1: \"Hi no Ito Rinne no Gemini (緋ノ糸輪廻ノGEMINI)\" by petit milady (ep 1)",
"#2: \"Magna Idea (マグナ・イデア)\" by fortuna (フォルトゥーナ) [Satsuki Ranjou (Ayana Taketatsu), Shizuno Urushibara (Aoi Yuuki), Haruka Momochi (Maaya Uchida), and Maya Shimon (Yui Ogura)] (eps 2-12)"
]
}
And The Part I'm Stuck On is the Genres Section because it has Multiple Genres with the Same Keys and I Don't Know how to Dynamically Display all of then in one Line of Text or one Sentence Rather
Here is the Genres Section of the JS:
"genres": [
{
"mal_id": 1,
"type": "anime",
"name": "Action",
"url": "https://myanimelist.net/anime/genre/1/Action"
},
{
"mal_id": 10,
"type": "anime",
"name": "Fantasy",
"url": "https://myanimelist.net/anime/genre/10/Fantasy"
},
{
"mal_id": 35,
"type": "anime",
"name": "Harem",
"url": "https://myanimelist.net/anime/genre/35/Harem"
},
{
"mal_id": 22,
"type": "anime",
"name": "Romance",
"url": "https://myanimelist.net/anime/genre/22/Romance"
},
{
"mal_id": 23,
"type": "anime",
"name": "School",
"url": "https://myanimelist.net/anime/genre/23/School"
},
{
"mal_id": 37,
"type": "anime",
"name": "Supernatural",
"url": "https://myanimelist.net/anime/genre/37/Supernatural"
}
],
So Here is The Question, How Do I Display All The Genres Like This " Genres: Action, Fantasy, Harem, Romance, School, Supernatural "? and Have it Display like this if There are more genres than these?
If you want to get a string with the names of the genres, you could use .map() and .join(). Use .map() to turn the array into an array of genre names, from an array of objects. Then use .join() to combine the array into a string.
var data = {
"request_hash": "request:anime:06c1f9aadcb4e3286fa86947ba8451bfc8c6d3a7",
"request_cached": true,
"request_cache_expiry": 73254,
"mal_id": 22663,
"url": "https://myanimelist.net/anime/22663/Seiken_Tsukai_no_World_Break",
"image_url": "https://cdn.myanimelist.net/images/anime/7/71769.jpg",
"trailer_url": "https://www.youtube.com/embed/zGXx54r4yWU?enablejsapi=1&wmode=opaque&autoplay=1",
"title": "Seiken Tsukai no World Break",
"title_english": "World Break: Aria of Curse for a Holy Swordsman",
"title_japanese": "聖剣使いの禁呪詠唱〈ワールドブレイク〉",
"title_synonyms": [
"Seiken Tsukai no Kinshuu Eishou",
"Warubure"
],
"type": "TV",
"source": "Light novel",
"episodes": 12,
"status": "Finished Airing",
"airing": false,
"aired": {
"from": "2015-01-12T00:00:00+00:00",
"to": "2015-03-30T00:00:00+00:00",
"prop": {
"from": {
"day": 12,
"month": 1,
"year": 2015
},
"to": {
"day": 30,
"month": 3,
"year": 2015
}
},
"string": "Jan 12, 2015 to Mar 30, 2015"
},
"duration": "24 min per ep",
"rating": "R - 17+ (violence & profanity)",
"score": 6.93,
"scored_by": 117100,
"rank": 3889,
"popularity": 602,
"members": 228214,
"favorites": 813,
"synopsis": "Seiken Tsukai no World Break takes place at Akane Private Academy where students who possess memories of their previous lives are being trained to use Ancestral Arts so that they can serve as defenders against monsters, called Metaphysicals, who randomly attack. Known as saviors, the students are broken up into two categories: the kurogane who are able to use their prana to summon offensive weapons and the kuroma who are able to use magic. The story begins six months prior to the major climax of the series during the opening ceremonies on the first day of the school year. After the ceremony is over, the main character, Moroha Haimura, meets a girl named Satsuki Ranjou who reveals that she was Moroha's little sister in a past life where Moroha was a heroic prince capable of slaying entire armies with his sword skills. Soon afterwards he meets another girl, Shizuno Urushibara, who eventually reveals that she also knew Moroha in an entirely different past life where he was a dark lord capable of using destructive magic but saved her from a life of slavery. Can those whose minds live in both the present and the past truly reach a bright future? Delve into the complex world of Seiken Tsukai no World Break to find out!",
"background": null,
"premiered": "Winter 2015",
"broadcast": "Mondays at 01:05 (JST)",
"related": {
"Adaptation": [{
"mal_id": 57101,
"type": "manga",
"name": "Seiken Tsukai no World Break",
"url": "https://myanimelist.net/manga/57101/Seiken_Tsukai_no_World_Break"
}]
},
"producers": [{
"mal_id": 64,
"type": "anime",
"name": "Sotsu",
"url": "https://myanimelist.net/anime/producer/64/Sotsu"
}],
"licensors": [{
"mal_id": 102,
"type": "anime",
"name": "Funimation",
"url": "https://myanimelist.net/anime/producer/102/Funimation"
}],
"studios": [{
"mal_id": 51,
"type": "anime",
"name": "Diomedea",
"url": "https://myanimelist.net/anime/producer/51/Diomedea"
}],
"genres": [{
"mal_id": 1,
"type": "anime",
"name": "Action",
"url": "https://myanimelist.net/anime/genre/1/Action"
},
{
"mal_id": 10,
"type": "anime",
"name": "Fantasy",
"url": "https://myanimelist.net/anime/genre/10/Fantasy"
},
{
"mal_id": 35,
"type": "anime",
"name": "Harem",
"url": "https://myanimelist.net/anime/genre/35/Harem"
},
{
"mal_id": 22,
"type": "anime",
"name": "Romance",
"url": "https://myanimelist.net/anime/genre/22/Romance"
},
{
"mal_id": 23,
"type": "anime",
"name": "School",
"url": "https://myanimelist.net/anime/genre/23/School"
},
{
"mal_id": 37,
"type": "anime",
"name": "Supernatural",
"url": "https://myanimelist.net/anime/genre/37/Supernatural"
}
],
"opening_themes": [
"\"Hi no Ito Rinne no Gemini (緋ノ糸輪廻ノGEMINI)\" by petit milady (eps 2-11)"
],
"ending_themes": [
"#1: \"Hi no Ito Rinne no Gemini (緋ノ糸輪廻ノGEMINI)\" by petit milady (ep 1)",
"#2: \"Magna Idea (マグナ・イデア)\" by fortuna (フォルトゥーナ) [Satsuki Ranjou (Ayana Taketatsu), Shizuno Urushibara (Aoi Yuuki), Haruka Momochi (Maaya Uchida), and Maya Shimon (Yui Ogura)] (eps 2-12)"
]
}
console.log(data.genres.map(e => e.name).join(", "))

access javascript value within the <script> tag with xpath

from this tag:
<script type = "text/javascript" > dataLayer.push({
"pageType": "productPage", "ecommerce": {
"currencyCode": "EUR",
"detail": {
"actionField": {"list": "Detail", "action": "detail"},
"products": [{
"name": "Desodorante Spray Alien",
"id": "10483558",
"price": "34,95",
"brand": "MUGLER",
"category": "higiene\/desodorantes",
"variant": "100 ML",
"dimension5": "Mucho stock",
"dimension6": "Unisex",
"dimension7": "CLARINS SPAIN, S.A",
"dimension8": "No",
"dimension9": "",
"metric2": 1
}]
},
"impressions": [{
"name": "Angel men recarga Eau de Toilette",
"id": "10059432",
"price": "47.95",
"brand": "MUGLER",
"category": "perfumes_hombre_edt",
"variant": "100 ML ",
"list": "you may want",
"position": 1
}, {
"name": "Angel men rubber flask Eau de Toilette",
"id": "10351154",
"price": "42.95",
"brand": "MUGLER",
"category": "perfumes_hombre_edt",
"variant": "50 ML ",
"list": "you may want",
"position": 2
}, {
"name": "Alien Shower Milk",
"id": "10483565",
"price": "26.00",
"brand": "MUGLER",
"category": "higiene_geles",
"variant": "200 ML ",
"list": "you may want",
"position": 3
}, {
"name": "Amen Desodorante en Stick",
"id": "10532706",
"price": "21.95",
"brand": "MUGLER",
"category": "hombre_desodorantes",
"variant": "75 ML ",
"list": "you may want",
"position": 4
}]
}
});
(window["rrApiOnReady"] = window["rrApiOnReady"] || []).push(function () {
retailrocket.productsGroup.post({
"groupId": 10483558,
"name": "Desodorante Spray Alien",
"price": 34.95,
"pictureUrl": "https://ima.douglas.es/img/1467/desodorante_spray_alien-0-.png",
"url": "https://douglas.es/p/mugler/desodorante_spray_alien",
"isAvailable": true,
"categoryPaths": ["Higiene/Corporal", "Corporal", "Corporal/Higiene", "Higiene", "Higiene/Desodorante", "Marca/Mugler"],
"description": "El elixir de feminidad y de sensualidad del Eau de Parfum Alien en su versión desodorante en spray. Déjate envolver con los mismos acordes de la fragancia.",
"vendor": "MUGLER",
"products": {
"10483558": {
"isAvailable": true,
"name": "Desodorante Spray Alien",
"size": "100",
"url": "https://douglas.es/p/mugler/desodorante_spray_alien",
"pictureUrl": "https://ima.douglas.es/img/1467/desodorante_spray_alien-0-.png",
"price": 34.95,
"oldPrice": 34.95,
"params": {}
}
},
"params": {"medida": "ML", "subTitle": "Todo tipo de piel"},
"model": "Desodorante Spray Alien",
"typePrefix": "higiene_desodorantes",
"oldPrice": 34.95
});
rrApi.groupView([10483558]);
});
App.page.webshop = "DOU";
App.page.warehouse = ["ALM"];
App.page.codPostal = "";
</script>
I need to access some specific values of different functions (products, products.brand, impressions and impressions.id).
I tried to convert it to json dictionary, but it is a list and it gets converted into an array and I cannot access it with a "name" value.
How can I do this?
An example would be to select the script using some unique keyword which is only present in this script. Once you have that, you can use re_first to get the desired value. Take this as an example:
product_css = "script:contains('productPage')::text"
regex = 'name": "(.+?)"'
product_name = response.css(product_count_css).re_first(regex)
This will extract the first name. You can use re to tweak it further. Best of luck.

How to return value from a unique key when I have a list of JSON objects? [duplicate]

This question already has answers here:
How to find first element of array matching a boolean condition in JavaScript?
(14 answers)
Closed 3 years ago.
I have a list of JSON objects, and I want to access the one with the key called "91842301" for example. See the code below.
How can I do this?
I have tried using functions such as find, where, propertyOf and others, but these do not take into consideration that I am searching through a list of objects that I know only the key of and not the placement in the list.
[{
"918345787": [
{
"year": "2018",
"name": "Lucidtech AS",
"organizationNumber": "918345787",
"employees": "5",
"currency": "NOK",
"totalOperatingIncome": 481000,
"personnelExpenses": 900000,
"salaryCosts": 741000,
"operatingProfit": -1043000,
"netIncome": -1042000,
"timestamp": "2019-7-2 13:30:16",
"daughter": "No avaliable information about daughters"
},
{
"year": "2017",
"name": "Lucidtech AS",
"organizationNumber": "918345787",
"employees": "unknown",
"currency": "NOK",
"totalOperatingIncome": 300000,
"personnelExpenses": 813000,
"salaryCosts": 710000,
"operatingProfit": -622000,
"netIncome": -621000,
"timestamp": "2019-7-2 13:30:16",
"daughter": "No avaliable information about daughters"
}
]
},
{
"979369867": [
{
"year": "2018",
"name": "Sikom AS",
"organizationNumber": "979369867",
"employees": "11",
"currency": "NOK",
"totalOperatingIncome": 18448000,
"personnelExpenses": 5563000,
"salaryCosts": null,
"operatingProfit": 275000,
"netIncome": 56000,
"timestamp": "2019-7-2 13:30:37",
"daughter": "No avaliable information about daughters"
},
{
"year": "2017",
"name": "Sikom AS",
"organizationNumber": "979369867",
"employees": "unknown",
"currency": "NOK",
"totalOperatingIncome": 15467000,
"personnelExpenses": 3453000,
"salaryCosts": 2758000,
"operatingProfit": -1000,
"netIncome": 74000,
"timestamp": "2019-7-2 13:30:37",
"daughter": "No avaliable information about daughters"
}
]
}]
You could check if the key exists and take this object.
key = '8980243'
result = data.find(object => key in object);
Use find to find something in an array.
Use in to test if a property exists.
const that_which_is_sought = "91842301";
const found_object = your_array.find( object_in_array => that_which_is_sought in object_in_array );
If I understood well what you want, here is a workable example:
let findKey = "918345787";
let array = [{
"918345787": [
{
"year": "2018",
"name": "Lucidtech AS",
"organizationNumber": "918345787",
"employees": "5",
"currency": "NOK",
"totalOperatingIncome": 481000,
"personnelExpenses": 900000,
"salaryCosts": 741000,
"operatingProfit": -1043000,
"netIncome": -1042000,
"timestamp": "2019-7-2 13:30:16",
"daughter": "No avaliable information about daughters"
},
{
"year": "2017",
"name": "Lucidtech AS",
"organizationNumber": "918345787",
"employees": "unknown",
"currency": "NOK",
"totalOperatingIncome": 300000,
"personnelExpenses": 813000,
"salaryCosts": 710000,
"operatingProfit": -622000,
"netIncome": -621000,
"timestamp": "2019-7-2 13:30:16",
"daughter": "No avaliable information about daughters"
}
]
},
{
"979369867": [
{
"year": "2018",
"name": "Sikom AS",
"organizationNumber": "979369867",
"employees": "11",
"currency": "NOK",
"totalOperatingIncome": 18448000,
"personnelExpenses": 5563000,
"salaryCosts": null,
"operatingProfit": 275000,
"netIncome": 56000,
"timestamp": "2019-7-2 13:30:37",
"daughter": "No avaliable information about daughters"
},
{
"year": "2017",
"name": "Sikom AS",
"organizationNumber": "979369867",
"employees": "unknown",
"currency": "NOK",
"totalOperatingIncome": 15467000,
"personnelExpenses": 3453000,
"salaryCosts": 2758000,
"operatingProfit": -1000,
"netIncome": 74000,
"timestamp": "2019-7-2 13:30:37",
"daughter": "No avaliable information about daughters"
}
]
}]
//Traditional form
for (let i=0; i<array.length; i++) {
if (array[i][findKey] != undefined) {
console.log("Traditional From:");
console.log(array[i][findKey]);
}
}
//Pro form:
let elements = array.filter(element => element[findKey] != undefined);
console.log("Pro Form!");
console.log(elements);

Aurelia - repeat.for json

I am new to Aurelia.
I'm trying to iterate (repeat.for) through some json that looks like below. I am able to do so with a manual concat but the number of artists is variable. Below for example works.
return this.http.fetch(baseUrl + "/artists/" + token + "&search=" + searchCreator)
.then(response => response.json())
.then(response => {
//for (var i = 0; i < response.resultsCount; i++){
// response += response.artists[i].objects;
//}
return response.artists[0].objects.concat(response.artists[1].objects);
});
How can I return all objects for all artists? I've tried doing this with a for loop but I can't get it to work. Should I return response.artists and then work with that in my view model? This is what the view looks like:
<tr repeat.for="item of items">
<td>${item.title}</td>
<td>${item.displayName}</td>
<td>${item.objectNumber}</td>
</tr>
json example:
{
"source": "My Museum",
"language": "EN",
"resultsCount": ​58,
"artists":
[{
"artistID": ​47171,
"alphaSort": "Smith Eloise Vega",
"displayName": "Eloise Vega Smith",
"beginDate": "0",
"endDate": "0",
"displayDate": "",
"sex": "Female",
"nationality": "",
"objectCount": ​1,
"objects":
[{
"objectNumber": "209.2015",
"objectID": ​188963,
"title": "Album cover for Urszula Dudziak, Newborn Light",
"displayName": "Eloise Vega Smith",
"alphaSort": "Smith Eloise Vega",
"artistID": ​47171,
"displayDate": "",
"dated": "1974",
"dateBegin": ​1974,
"dateEnd": ​1974,
"medium": "Lithograph",
"dimensions": "12 1/2 x 12 1/4\" (31.8 x 31.1 cm)",
"department": "Architecture & Design",
"classification": "A&D Graphic Design",
"onView": ​0,
"provenance": "",
"description": "",
"objectStatusID": ​1,
"creditLine": "Committee on Architecture and Design Funds",
"imageID": "502407",
"thumbnail": "http:///TMSImages/Size1/Images/TR15211_10_RICR.jpg",
"fullImage": "http:///TMSImages/Size3/Images/TR15211_10_RICR.jpg",
"lastModifiedDate": "2015-09-17T01:00:08"
}
]
},
{
"artistID": ​5479,
"alphaSort": "Smith Charles",
"displayName": "Charles Smith",
"beginDate": "1893",
"endDate": "1987",
"displayDate": "American, 1893–1987",
"sex": "Male",
"nationality": "American",
"objectCount": ​6,
"objects":
[{
"objectNumber": "369.1941",
"objectID": ​67911,
"title": "Red Circle",
"displayName": "Charles Smith",
"alphaSort": "Smith Charles",
"artistID": ​5479,
"displayDate": "American, 1893–1987",
"dated": "1940",
"dateBegin": ​1940,
"dateEnd": ​1940,
"medium": "Monoprint",
"dimensions": "Sheet 21 1/8 x 14 3/4\" (53.8 x 37.5 cm) Comp. 20 x 14 3/4\" (50.8 x 37.5 cm)",
"department": "Prints & Illustrated Books",
"classification": "Print",
"onView": ​0,
"provenance": "",
"description": "Color monoprint, printed from movable forms",
"objectStatusID": ​1,
"creditLine": "Purchase",
"imageID": "260293",
"thumbnail": "http:///TMSImages/Size1/Images/369_1941_RICR.jpg",
"fullImage": "http:///TMSImages/Size3/Images/369_1941_RICR.jpg",
"lastModifiedDate": "2015-03-31T01:06:18"
},
{
"objectNumber": "214.1942",
"objectID": ​64517,
"title": "Abstraction",
"displayName": "Charles Smith",
"alphaSort": "Smith Charles",
"artistID": ​5479,
"displayDate": "American, 1893–1987",
"dated": "c. 1942",
"dateBegin": ​1942,
"dateEnd": ​1942,
"medium": "Woodcut",
"dimensions": "composition (irreg.): 11 1/4 x 3 3/4\" (28.5 x 9.6 cm); sheet: 14 9/16 x 7 1/16\" (37 x 17.9 cm)",
"department": "Prints & Illustrated Books",
"classification": "Print",
"onView": ​0,
"provenance": "",
"description": "Woodcut, printed in black, dark green yellow, deep blue and strong red brown",
"objectStatusID": ​1,
"creditLine": "Given anonymously",
"imageID": "195213",
"thumbnail": "http:///TMSImages/Size1/Images/214_1942_RICR.jpg",
"fullImage": "http:///TMSImages/Size3/Images/214_1942_RICR.jpg",
"lastModifiedDate": "2014-09-19T01:05:22"
},
etc.....
I appreciate the help!
If you are familiar with LINQ, you could use a library like jslinq and do the following:
return jslinq(response.artists)
.selectMany(function(artist){
return artist.objects
}).toList();
of course I would only include jslinq if I planned to use it more than once in the project. If you don't want the overhead, your solution with concat should work just fine:
var result = [];
for(var i = 0; i < response.artists.length; i++) {
result = result.concat(response.artists[i].objects);
}
return result;

Categories