HTML String in JSON - json

I know it isn’t the best idea to have html in your JSON but sadly I am not in control of this database or this website and am not given those privileges! I am making google maps markers and one of the values is corrupting the data and not being processed right. I know the issue is in the DESC value, is there some sort of character that isn’t escaped? Because almost all of the other objects in the JSON work just fine besides this one.
{"PHONE":"847-509-2000”,
"LAT":42.15223,
"STATE":"IL”,
"ZIP":60015.0,
"NAME":"DC Sarnies”,
"DESC":"Opening in early May 2011, D.C. Sarnies is a contemporary but casual restaurant
specializing in sandwiches and classic American food with a twist. As well as a
restaurant, we serve as a research and development kitchen for its parent company,
Highland Baking Company. Guest chefs and bakery clients will have the opportunity to try
out new products and let diners provide feedback on the dishes. The menu at D. C. Sarnies
has something for everyone with a wide variety of appetizers, soups, salads, entrees and
signature sandwiches and burgers to choose from. A full bar also gives diners a wide range
of craft beers including more than 25 on tap, wine and cocktails. For more information
visit us on Facebook at D.C. Sarnies or on Twitter DC_Sarnies.”,
"LONG":-87.84241,
"CITY":"Deerfield”,
"ADDR":"649 Lake Cook Road”,
"PHOTO":"DCcrabcakeburger.jpg”}]
jsonlint error message: Parse error on line 74:
...02, "DESC": "Opening in early Ma
----------------------^
Expecting 'STRING', 'NUMBER', 'NULL', 'TRUE', 'FALSE', '{', '['

http://jsonlint.org/ use this website to validate your JSON.
The problem here are the closing quotes you use for strings, they're invalid.

End double quotes wrong. Rest everything is fine and working.

The double quotes at the end of the values are the problem. They're the wrong character.

There are a couple issues:
Different quotes used. ” is different from ".
Multi-line isn't escaped. If you need the line breaks, use \n. Otherwise, just have it one line
The extra ] at the end shouldn't be there
This is what you should have:
{
"PHONE": "847-509-2000",
"LAT": 42.15223,
"STATE": "IL",
"ZIP": 60015,
"NAME": "DC Sarnies",
"DESC": "Opening in early May 2011, D.C. Sarnies is a contemporary but casual restaurant specializing in sandwiches and classic American food with a twist. As well as a restaurant, we serve as a research and development kitchen for its parent company, Highland Baking Company. Guest chefs and bakery clients will have the opportunity to try out new products and let diners provide feedback on the dishes. The menu at D. C. Sarnies has something for everyone with a wide variety of appetizers, soups, salads, entrees and signature sandwiches and burgers to choose from. A full bar also gives diners a wide range of craft beers including more than 25 on tap, wine and cocktails. For more information visit us on Facebook at D.C. Sarnies or on Twitter DC_Sarnies.",
"LONG": -87.84241,
"CITY": "Deerfield",
"ADDR": "649 Lake Cook Road",
"PHOTO": "DCcrabcakeburger.jpg"
}

Related

Combining Several Character Objects into a Single Object

I am trying to scrape text from a news article - I am doing this as follows:
library(rvest)
url <- "https://www.bbc.com/future/article/20220823-how-auckland-worlds-most-spongy-city-tackles-floods"
final = url %>%
read_html() %>%
html_elements(".article__body-content p") %>%
html_text()
This seems to have worked, but I am trying to combine the results of this code into a single object. For example, the current results look like this:
[1] "Tangled mats of muddy vegetation line the footpaths of Underwood Park, a narrow stripe of green winding along a creek beneath the small volcanic cone of Ōwairaka (Mt Albert) in Auckland, New Zealand. In the water, clumps of sticks and the occasional plastic bag are marooned on protruding rocks and branches."
[2] "A winter storm swept through the city overnight, dropping heavy rain, and Te Auaunga (Oakley Creek), one of the city’s longest urban streams, has overflowed its banks."
[3] "\"But that’s supposed to happen,\" says Julie Fairey, chair of the Puketāpapa local board, who is showing me around Underwood and the neighbouring Walmsley Park."
I would like to make a single object of this text - for example (remove all " "):
final <- "Tangled mats of muddy vegetation line the footpaths of Underwood Park, a narrow stripe of green winding along a creek beneath the small volcanic cone of Ōwairaka (Mt Albert) in Auckland, New Zealand. In the water, clumps of sticks and the occasional plastic bag are marooned on protruding rocks and branches.
A winter storm swept through the city overnight, dropping heavy rain, and Te Auaunga (Oakley Creek), one of the city’s longest urban streams, has overflowed its banks.
But that’s supposed to happen, says Julie Fairey, chair of the Puketāpapa local board, who is showing me around Underwood and the neighbouring Walmsley Park."
When I inspect the results, I initially thought it was a list - but it's actually a character object. Had this been a list, I could have used the "unlist" command. But now I am not sure how to proceed.
Can someone please show me how to proceed?
Thanks!
The output from html_text is a vector of strings. We could join them as a single string with paste and collapse.
library(rvest)
library(magrittr)
final <- url %>%
read_html() %>%
html_elements(".article__body-content p") %>%
html_text() %>%
paste(collapse = "\n")
Now, we check the output
cat(final, sep = "\n")
Tangled mats of muddy vegetation line the footpaths of Underwood Park, a narrow stripe of green winding along a creek beneath the small volcanic cone of Ōwairaka (Mt Albert) in Auckland, New Zealand. In the water, clumps of sticks and the occasional plastic bag are marooned on protruding rocks and branches.
A winter storm swept through the city overnight, dropping heavy rain, and Te Auaunga (Oakley Creek), one of the city’s longest urban streams, has overflowed its banks.
"But that’s supposed to happen," says Julie Fairey, chair of the Puketāpapa local board, who is showing me around Underwood and the neighbouring Walmsley Park.
The connected parks are designed to collect excess stormwater, soak it up like a sponge, and slowly release it back into the creek. The debris left behind is evidence this "secret infrastructure" is working, Fairey says. The two parks are flanked on both sides by public housing developments. "This stuff is designed to flood so that the houses don’t," she says.
It wasn’t always this way, Fairey tells me, as we watch a black shag drying its wings on a rock. Less than a decade ago, the waterway was a concrete-lined culvert that ran through seldom-visited muddy fields. When it flooded, water sloshed into the surrounding suburbs. It collected engine oil, sediment and rubbish and sucked this unhealthy mixture out into the city’s famous harbour, rendering the beaches unsafe to swim.
But in 2016, work began to free Te Auaunga from rigid concrete, and restore it to a more natural, meandering shape. Its banks are now lush with native vegetation like harakeke (flax) and tī kouka (cabbage trees), as well as reeds, ferns and other filtering wetland plants.
The changes have increased this part of the city’s ability to absorb excess rainfall, an attribute sometimes called “sponginess”. Auckland was recently named the most spongy global city in a report by multinational architecture and design firm Arup, thanks to its geography, soil type, and urban design – but experts warn it may not lead the pack for long.
As climate change intensifies extreme weather events worldwide, what can other cities learn from Auckland's successes – and failures?
The connected parks around Te Auaunga creek in Auckland are designed to soak up excess stormwater like a sponge (Credit: Kate Evans)
....

Extract Image url from WordPress REST API JSON response

I'm new to WordPress REST API and I don't know how to extract the image URLs from the "content" key of the API (https://www.example.com/wp-json/wp/v2/posts) response which looks like this:
"content": {
"rendered": "\n<p>From munching on a casual pizza to romantic candlelit dinner in Kolkata with your better half, Valentine’s week is filled with all of these!</p>\n\n\n\n<p>The love week of February offers the perfect excuse to sample Kolkata’s very best restaurants with your other half.</p>\n\n\n\n<p>Find your dream date night in our Valentine’s Day special guide to the cutest restaurants in Kolkata.</p>\n\n\n\n<h2><i><center>Blue and Beyond</center></i></h2>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img src=\"https://kolkatasutra.com/wp-content/uploads/2021/02/blue-n-beyond.png\" alt=\"\" class=\"wp-image-919\" srcset=\"https://kolkatasutra.com/wp-content/uploads/2021/02/blue-n-beyond.png 540w, https://kolkatasutra.com/wp-content/uploads/2021/02/blue-n-beyond-300x197.png 300w, https://kolkatasutra.com/wp-content/uploads/2021/02/blue-n-beyond-150x99.png 150w\" sizes=\"(max-width: 540px) 100vw, 540px\" /><figcaption>Blue & Beyond, New Market</figcaption></figure></div>\n\n\n\n<p>Situated in the New Market area, this place boasts of beautiful rooftop open-air seating. It also has an indoor seating</p>\n\n\n\n<p>You can expect a feel of colonial Kolkata with Stuart Hogg Market below."
}
I tried this solution, but the "featured_media" is 0 in my case.
Installed this plugin, but the field "better_featured_image" is showing as null in all the posts.
This is the only solution that might solve the problem, but I don't know how to extract Image URLs using Regex.
Please help me with the Regex to extract the URLs. Or if there's another way which might help, please mention in the ans.
You can decode json string usgin json_decode() fucntion. then you can preg_match to match with '/src="([^"]*)"/' regex that extract your src. check below code.
<?php
$image = '{"content": {"rendered": "\n<p>From munching on a casual pizza to romantic candlelit dinner in Kolkata with your better half, Valentine’s week is filled with all of these!</p>\n\n\n\n<p>The love week of February offers the perfect excuse to sample Kolkata’s very best restaurants with your other half.</p>\n\n\n\n<p>Find your dream date night in our Valentine’s Day special guide to the cutest restaurants in Kolkata.</p>\n\n\n\n<h2><i><center>Blue and Beyond</center></i></h2>\n\n\n\n<div class=\"wp-block-image\"><figure class=\"aligncenter\"><img src=\"https://kolkatasutra.com/wp-content/uploads/2021/02/blue-n-beyond.png\" alt=\"\" class=\"wp-image-919\" srcset=\"https://kolkatasutra.com/wp-content/uploads/2021/02/blue-n-beyond.png 540w, https://kolkatasutra.com/wp-content/uploads/2021/02/blue-n-beyond-300x197.png 300w, https://kolkatasutra.com/wp-content/uploads/2021/02/blue-n-beyond-150x99.png 150w\" sizes=\"(max-width: 540px) 100vw, 540px\" /><figcaption>Blue & Beyond, New Market</figcaption></figure></div>\n\n\n\n<p>Situated in the New Market area, this place boasts of beautiful rooftop open-air seating. It also has an indoor seating</p>\n\n\n\n<p>You can expect a feel of colonial Kolkata with Stuart Hogg Market below."}}';
$image = json_decode($image, true);
preg_match('/src="([^"]*)"/',$image['content']['rendered'], $result);
echo $result[1]; die;
?>

Google rejecting Facebooks json-ld required tags

I am setting up JSON+LD tags on my product pages for Facebooks "Dynamic Ads & Commerce".
https://developers.facebook.com/docs/marketing-api/catalog/reference/
Two tags it states are required:
id
Required for dynamic ads and commerce.
availability
Required for dynamic ads and commerce.
I've added these, but it causes Google to reject my json+ld markup.
Invalid enum value in field 'availability'
1.
2.
How could I please both parties here? If I am adding json+ld markup, it may as well have all required elements to be valid on Google and Facebook (Catalog).
[
{
"#context":"http:\/\/www.schema.org",
"#type":"Product",
"name":"Silentnight Safe Nights Toddler Bedset – 4.5 Tog",
"title":"Silentnight Safe Nights Toddler Bedset – 4.5 Tog",
"url":"http:\/\/myexampledomain.co.uk\/product\/silentnight-safe-nights-toddler-bedset-4-5-tog\/",
"link":"http:\/\/myexampledomain.co.uk\/product\/silentnight-safe-nights-toddler-bedset-4-5-tog\/",
"image":"http:\/\/myexampledomain.co.uk\/app\/uploads\/sites\/3\/2019\/10\/silentnight-safe-nights-toddler-bedset-4.5-tog-pack.jpg",
"image_link":"http:\/\/myexampledomain.co.uk\/app\/uploads\/sites\/3\/2019\/10\/silentnight-safe-nights-toddler-bedset-4.5-tog-pack.jpg",
"description":"The Silentnight Toddler Duvet and Pillow set makes a great first bed set for your little one. The cot bed sized set includes a snuggly duvet and a soft pillow that is specially designed for children. The slim profile of the pillow offers your child just the right amount of support they need. It's important that small children don't overheat in bed, so the light and soft duvet comes in a 4.5 tog weight rating. Both the pillow and duvet are made from a smooth polycotton cover offering breathable comfort. The products are filled with anti-allergy hollowfibre that actively defends against the bacteria and dust mites that can cause allergies providing a cleaner, fresher and altogether a safer option for a good night's sleep. Our anti-allergy fibres are approved by the British Allergy Foundation, which means they have the ultimate seal of approval. Our fibres have been scientifically tested and are proven to reduce or remove allergens from the indoor environment.\nSuitable only for children over 12 months. Both the pillow and duvet are fully machine washable, and thanks to the easy care polycotton covers, the products have great recovery and can be washed time and time again.",
"sku":"506984LS",
"id":17214,
"productID":17214,
"offers":[
{
"#type":"Offer",
"price":"30.99",
"priceCurrency":"GBP",
"url":"http:\/\/myexampledomain.co.uk\/product\/silentnight-safe-nights-toddler-bedset-4-5-tog\/",
"gtin":"5012701506984",
"gtin8":"5012701506984",
"condition":"new",
"availability":"in stock",
"inventoryLevel":54
}
],
"brand":"Silentnight"
}
]

Display Sub content from ngFor Array on Click

In my project I have, each of the card values displayed on the screen they are looped over from JSON using ngFor. The desired goal is when a user clicks on a card it displays just the information about that card from the JSON while just showing the content in my div with an *ngIf. I have an animation created to fade in a mask where I want the content displayed. Currently if you click on the card it just shows the array of thumbnails. I'm not getting any errors or anything to go on. I've tirelessly searched for answers on how to accomplish showing an individual key on a click. I need the Card image, name, and description displayed for a single card at a time. I feel like I've hit a road block and am not Googling the correct description. Please let me know if I need to further clarify. Thank you for any direction you can offer.
[
{
"id": 1,
"content": [
{
"sin": "Vanity",
"card": "/assets/img/vanity.jpg",
"icon": "/assets/img/vanityIcon.jpg",
"info": "In almost every list pride (or hubris or vanity) is considered the original and most serious of the seven deadly sins, and indeed the ultimate source from which the others arise. It is identified as a desire to be more important or attractive than others, failing to acknowledge the good work of others, and excessive love of self (especially holding self out of proper position toward God). Dante's definition was 'love of self perverted to hatred and contempt for one's neighbor.' In Jacob Bidermann's medieval miracle play, Cenodoxus, pride is the deadliest of all the sins and leads directly to the damnation of the titulary famed Parisian doctor. In perhaps the best-known example, the story of Lucifer, pride (his desire to compete with God) was what caused his fall from Heaven, and his resultant transformation into Satan. Vanity and narcissism are prime examples of this sin. In Dante's Divine Comedy, the penitents were forced to walk with stone slabs bearing down on their backs in order to induce feelings of humility."
}
]
},
{
"id": 2,
"content": [
{
"sin": "Envy",
"card": "/assets/img/envy.jpg",
"icon": "/assets/img/envyIcon.jpg",
"info": "Like greed, envy may be characterized by an insatiable desire; they differ, however, for two main reasons. First, greed is largely associated with material goods, whereas envy may apply more generally. Second, those who commit the sin of envy resent that another person has something they perceive themselves as lacking, and wish the other person to be deprived of it. Dante defined this as 'love of one's own good perverted to a desire to deprive other men of theirs.' In Dante's Purgatory, the punishment for the envious is to have their eyes sewn shut with wire because they have gained sinful pleasure from seeing others brought low. Aquinas described envy as 'sorrow for another's good'."
}
]
},
{
"id": 3,
"content": [
{
"sin": "Sloth",
"card": "/assets/img/sloth.jpg",
"icon": "/assets/img/slothIcon.jpg",
"info": "More than other sins, the definition of sloth has changed considerably since its original inclusion among the seven deadly sins. In fact it was first called the sin of sadness or despair. It had been in the early years of Christianity characterized by what modern writers would now describe as melancholy: apathy, depression, and joylessness — the last being viewed as being a refusal to enjoy the goodness of God and the world God created. Originally, its place was fulfilled by two other aspects, acedia and sadness. The former described a spiritual apathy that affected the faithful by discouraging them from their religious work. Sadness (tristitia in Latin) described a feeling of dissatisfaction or discontent, which caused unhappiness with one's current situation. When Thomas Aquinas selected acedia for his list, he described it as an 'uneasiness of the mind', being a progenitor for lesser sins such as restlessness and instability. Dante refined this definition further, describing sloth as being the 'failure to love God with all one's heart, all one's mind and all one's soul.' He also described it as the middle sin, and as such was the only sin characterised by an absence or insufficiency of love. In his 'Purgatorio', the slothful penitents were made to run continuously at top speed."
}
]
},
{
"id": 4,
"content": [
{
"sin": "Wrath",
"card": "/assets/img/wrath.jpg",
"icon": "/assets/img/wrathIcon.jpg",
"info": "Wrath (or anger or 'Rage') may be described as inordinate and uncontrolled feelings of hatred and anger. These feelings can manifest as vehement denial of the truth, both to others and in the form of self-denial, impatience with the procedure of law, and the desire to seek revenge outside of the workings of the justice system (such as engaging in vigilantism) and generally wishing to do evil or harm to others. The transgressions borne of vengeance are among the most serious, including murder, assault, and in extreme cases, genocide. Wrath is the only sin not necessarily associated with selfishness or self-interest (although one can of course be wrathful for selfish reasons, such as jealousy, closely related to the sin of envy). Dante described vengeance as 'love of justice perverted to revenge and spite'. In its original form, the sin of wrath also encompassed anger pointed internally rather than externally. Thus suicide was deemed as the ultimate, albeit tragic, expression of wrath directed inwardly, a final rejection of God's gifts."
}
]
},
{
"id": 5,
"content": [
{
"sin": "Lust",
"card": "/assets/img/lust.jpg",
"icon": "/assets/img/lustIcon.jpg",
"info": "Lust (or lechery) is usually thought of as excessive thoughts or desires of a sexual nature. Giving in to lusts can lead to sexual or sociological compulsions and/or transgressions including (but not limited to) sexual addiction, fornication, adultery, bestiality, rape, perversion, and incest. Dante's criterion was 'excessive love of others', which therefore rendered love and devotion to God as secondary. In 'Purgatorio', the penitent walks within flames to purge himself of lustful/sexual thoughts and feelings."
}
]
},
{
"id": 6,
"content": [
{
"sin": "Gluttony",
"card": "/assets/img/gluttony.jpg",
"icon": "/assets/img/gluttonyIcon.jpg",
"info": "Derived from the Latin gluttire, meaning to gulp down or swallow, gluttony is the over-indulgence and over-consumption of anything to the point of waste. In the Christian religions, it is considered a sin because of the excessive desire for food, or its withholding from the needy. Depending on the culture, it can be seen as either a vice or a sign of status. Where food is relatively scarce, being able to eat well might be something to take pride in (although this can also result in a moral backlash when confronted with the reality of those less fortunate). Where food is routinely plentiful, it may be considered a sign of self-control to resist the temptation to over-indulge."
}
]
},
{
"id": 7,
"content": [
{
"sin": "Greed",
"card": "/assets/img/greed.jpg",
"icon": "/assets/img/greedIcon.jpg",
"info": "Greed (or avarice, covetousness) is, like lust and gluttony, a sin of excess. However, greed (as seen by the church) is applied to the acquisition of wealth in particular. St. Thomas Aquinas wrote that greed was 'a sin against God, just as all mortal sins, in as much as man condemns things eternal for the sake of temporal things.'' In Dante's Purgatory, the penitents were bound and laid face down on the ground for having concentrated too much on earthly thoughts. 'Avarice' is more of a blanket term that can describe many other examples of greedy behavior. These include disloyalty, deliberate betrayal, or treason,[citations needed] especially for personal gain, for example through bribery . Scavenging[citation needed] and hoarding of materials or objects, theft and robbery, especially by means of violence, trickery, or manipulation of authority are all actions that may be inspired by greed. Such misdeeds can include simony, where one profits from soliciting goods within the actual confines of a church."
}
]
}
]
(Updated to include full JSON)
<!-- CARD CONTENT -->
<div class="table" *ngFor="let sins of cardwork; index as i">
<!-- CARD CONTENT -->
<div class="cardsLayedOut">
<a href="#" (click)="toggleCard(i)"> // User Clicks here
<img class="card" [ngStyle]="rotateCards()" *ngFor="let sublist of sins.content" [src]="sublist.card" />
</a>
</div>
<div class="" *ngIf="cards" #cards [#clickevent]>
<div class="mask columnCentered">
<div class="contentLayout" *ngFor="let sublist of sins[i]?.content">
<img class="largeCard" [src]="sublist[i]?.card" />
<div class="sinInfo">
<h3>{{sublist[i]?.sin}}</h3>
<p>{{sublist[i]?.info}}</p>
</div>
</div>
<app-thumnail></app-thumnail>
</div>
</div>
</div>
My toggle for hiding/showing the card information is
toggleCard() {
this.cards = true;
}
This is the current state when adding an array holder of cards = []; and in my toggleCard(i) this.cards[i] = !this.cards[i];
The second image is the desired state for each of the cards.
Your toggle function isn't right.
You are sending index i as an argument from your template (click)="toggleCard(i)" but aren't capturing it in your component.
You should capture that index i because it uniquely identifies the clicked card. If not how will you know which card is clicked?
toggleCard(var i) {
// Handle click event.
}
Also, you are just using one cards variable to toggle the state of all the cards. So if one card is clicked, all the cards are shown or hidden not just that clicked card.
You should have an array cards[] which takes boolean values and keeps track of toggle state of each card.
In your toggleCard() function, whenever a card is clicked, toggle appropriate value in this array based on the index i you are receiving.
var cards = []; // Initialize with boolean values.
// Array length would be equal to the number of your cards.
toggleCard(var i) {
this.cards[i] = !this.cards[i];
}
EDIT:
Regarding your problem after implementing suggested changes:
In your StackBlitz:
You are initializing selectedCard to false, but this variable takes number values. This shouldn't be an issue since JavaScript allows dynamic types.
There is a typo sin instead of sins in this statement <p>{{ sin.content.sin }}</p>. It should be <p>{{ sins.content.sin }}</p>.
Fix these and you should see all the cards.

how to display data in html

In my project, I am retrieving an address from the database and displaying this address on page. The issue or problem that I am facing is the the way the retrieved address is being displayed.
Basically this is the way the address is being displayed:
Address: 1 Kings Street Kilmarnock East Berkshire Scotland KA1 UIT
I would like the address to be displayed like so:
Address: 1 Kings Street
Kilmarnock
East Berkshire
Scotland
KA1 UIT
How can I do this in HTML or css? I am currently using twitter bootstrap , and I don't if there is anyway to do using it.
Oh.. It's hard but let me try... ;)
<div>Address: 1 Kings Street<br> Kilmarnock <br>East Berkshire<br> Scotland <br>KA1 UIT</div>
Your Expected Output:
Address: 1 Kings Street
Kilmarnock
East Berkshire
Scotland
KA1 UIT
Working Demo
Note: This is just simplest and basic way.. But if Data is coming from any database dynamically then at-least you should explain in details from where it comes and by which object it can be accessible.. Then you can apply JS or regex functions... I hope you understand what I mean..
If you edited the data in your database, and used a comma between each line, you might be able to split the data. (your question doesn't state what language you are writing in (mvc/how data is being received).
However, once you have the string, you can use the String.split method (available in most languages), and hence could adapt your view accordingly.
So,
Address: 1 Kings Street, Kilmarnock, East Berkshire, Scotland, KA1 UIT
would become
{1 Kings Street}{ Kilmarnock}{ East Berkshire}{ Scotland}{ KA1 UIT}
which you could then do a foreach block, displaying them onto the screen as you requested
A possible alternative (although probably not easy), would be to extract the postcode, and call a google maps API call to receive the address - but again, this would be quite difficult.
At present, I cannot see how you would be able to expect a program to decide where to split the address into separate lines (unless you place them into different fields which was described in the comments).
You can add <p> to each line, or put <br> at the end of each lines.
But
If your retrieving the data from a database through a php variable you cannot do that with pure html / css, you'll need string manipulation with PHP.