I'm just starting with JSON and JavaScript and I am having some difficulties parsing JSON result. This is because there is a variable array with within episodes array the JSON that I want to have. So this is an array in an array if I'm right.
Example code:
{
"description":"This is a description",
"banner":"This is a banner",
"episodes":{
"15":[
{
"id":"28685",
"active":1,
"lang":"en",
"link":"http:\/\/link.com\video.php?hd=1"
}
],
"14":[
{
"id":"28577",
"active":1,
"lang":"ru",
"link":"http:\/\/link.com\video.php?hd=1"
}
]};
The "15 and 14" are episode numbers, and id, active, lang, and links are properties from that episode.
So in HTML I want to display that as a group together. Can anyone help me out on this, because I can't find any results on the JQuery page how to get those variable episode number array name.
Maybe to make it a bit more clear. This is my JSON source, and i want to create a video page from it. Where it lists all these episodes with the properties. I'm planning on putting this together with the twitter bootstrap library. The description is the "description from the tv serie" banner is for the banner image, and the list above here are episode 15 and 14. I want to be able to click on such an episodelink. The only think i have difficulties with getting it all apart in different objects: Full json: http://pastie.org/6635498
And it needs to be dynamic this way if the Json updates it also updates the html, that way i can't make static references to "15"
Some quick html i've made to be the target idea: http://pastie.org/6635571
using jquery you can convert your json string (assuming it's a valid json string) to a javascript object like this:
var jsonObj = $.parseJSON('{
"description":"This is a description",
"banner":"This is a banner",
"episodes":{
"15":[
{
"id":"28685",
"active":1,
"lang":"en",
"link":"http:\/\/link.com\video.php?hd=1"
}
],
"14":[
{
"id":"28577",
"active":1,
"lang":"ru",
"link":"http:\/\/link.com\video.php?hd=1"
}
]}');
from here you can access the json data in javascript like this (e.g. for episode 15's id):
var episode15id = jsonObj['episodes']['15']['id'];
then thru javascript magic you can put that into your html:
html:
<div id="jsondatahere" ></div>
js:
$("#jsondatahere").html(episode15id);
Related
i'm currently trying to set up some JMeter testplans. I am pretty new to this (started a week ago) and don't have much programming experience either, so i hope you could help me in this case.
I already set up some http requests and have some simple JSON Extractor post processors to save some of the variables and use them with the "${variable}" notation.
But now i need to save and modify an object from a response to use that in the next http request.
My respose is a extremely big JSON object and the part im interested in looks something like this:
{
"payload": {
"workspace": {
"resultInstance": [
[{"part": "1"...}],
[{"part": "2"...}],
...
[{"part": "20"...}]
]
}
}
}
Note that for whatever reason these objects {"part":"1"...} are inside a nested array. And they are also pretty big.
I would like to safe those objects in a variable to use them in my next http request which should looks like this:
{
"instanceChange": {
"functionChecks": [
{"part": "1"...},
{"part": "2"...},
...
{"part": "20"...}
]
}
}
So what im really trying to find is a way to save all of the possible objects inside the nested array "resultInstance" and put them inside the non nested array "functionChecks".
I already looked inside the JMeter documentation but because of my poor programming background i cant find a way to realize this.
I think i need something like the JSR223 PostProcessor and "simply go through the resultInstance-array and use smth. like an getObject() on these", but i cant figure out the code i need and if its even possible to safe objects in variables in Jmeter.
Im pretty thankful for every bit of help or advice :).
Thanks in advance,
aiksn
Add JSR223 PostProcessor as a child of the request which returns the JSON response
Put the following code into "Script" area:
def response = new groovy.json.JsonSlurper().parse(prev.getResponseData())
def request = ['instanceChange': ['functionChecks': response.payload.workspace.resultInstance]]
vars.put('request', new groovy.json.JsonBuilder(request).toPrettyString())
That's it, you should be able to refer the generated request body as ${request} where required
More information:
Apache Groovy - Parsing and producing JSON
Apache Groovy - Why and How You Should Use It
let response ={
"payload": {
"workspace": {
"resultInstance": [
[{"part": "1"...}],
[{"part": "2"...}],
...
[{"part": "20"...}]
]
}
}
};
let requestObj={
"instanceChange": {
"functionChecks": [
]
}
};
response.payload.workspace.resultInstance.forEach(myFunction);
myFunction(item, index) {
requestObj.instance.functionsCheck.push(item[0]);
}
I am attempting to implement a large searchable table of information on a static website- so using SQL or PHP is not possible. I am considering using Datatables, and converting the CSV into HTML. However I feel that having a nearly 3000 long HTML table isn't the most efficient way of doing this? What would be the best way of doing this? Thanks.
Have two files, an HTML page (i.e. the datatable your users will use) and a JSON file where you will store all your data.
Then, use fetch() to retrieve the data from the JSON file into the HTML page.
Say you wanted to display a datatable with two fields - names and DOBs - your JSON would look something like this:
{
[
["John Doe", "5.4.1996"],
["Jane Doe", "5.4.2006"]
]
}
On the HTML page:
let response = await fetch(url);
if (response.ok) { // if HTTP-status is 200-299
// get the response body (the method explained below)
let json = await response.json();
// TODO: put the retrieved json into the datable
} else {
alert("HTTP-Error: " + response.status);
}
context
I am turning an old php ecommerce site into a static site built with gatsby.js.
I put all my product metadata into separate .json files (one per product) and I am able to load them with json and file transformer plugins. They are in /items. However each item is related to a set of standard images... eg item-01-main.jpg, item-01-placement.jpg, etc... I put all the images together in /itemphotosand followed the instructions here to load them into graphql: https://www.gatsbyjs.org/packages/gatsby-image/
question
On the page that loads all the products, i have no idea how to incorporate each one's item-xx-main.jpg image: I don't know what graphql query would fetch BOTH sets of data and match/merge them.:
/items
item-01.json
item-02.json
/itemphotos
item-01-main.jpg
item-01-placement.jpg
item-02-main.jpg
item-02-placement.jpg
I have a feeling my directory structure was the wrong approach and maybe I should store all the related images with my product json together in a folder:
/items
item-01/
item-01.json
item-01-main.jpg
item-01-placement.jpg
item-02/
item-02.json
item-02-main.jpg
item-02-placement.jpg
But then how do I source an items/ directory made up of item-xx/ subfolders holding both images and json, as representing a single entity, in graphql?
I did not go with markdown files because I wanted max UI flexibility.
Structure 2
Can you reference your images inside the .json? If so, the 2nd structure could be the winner, since you won't have to do much extra work:
// item-01.json
{
"meta": "...",
"main": "./item-01-main.jpg",
"placement": "./item-01-placement.jpg"
}
Query:
{
json {
id
main {
childImageSharp {
fixed {
src
}
}
}
}
}
Structure 1
If that's not possible or if you'd like to keep the 1st structure, you can try this query:
{
item: allFile(filter: { relativePath: { regex: "/item-01/" } }) {
nodes {
name
extension
children {
... on ImageSharp {
fixed {
src
}
}
... on Item01Json {
id
}
}
}
}
}
This will yield an array containing all files that share the same item id, regardless where they are stored. You can then use extension field to find the json & jpg nodes. It's not pretty, but it also doesn't require that much additional work.
None of the above
If none of that works for you, you could explore adding a image field to the json's graphql schema with createTypes and createResolvers. Add a type definition for the json via createTypes, then use createResolvers to locate the imageSharp node & resolve it.
A more clear cut example can be found from their code repo this page. This uses the same method as #Derek discussed. But if you want an example to understand more.
For reasons I won't bore you with, ALL elements of my webpage must be embedded into one file.
Between the HTML header tags, I have valid JSON data declared:
<script type="application/json" id="data">
"name": "flare", "children":[{"name": "thing1", ... }]
</script>
Previously this data was written to a JSON file which was referenced by my D3 bar chart scripts as follows:
d3.json("data/file.json", function(root) {
hierarchy.nodes(root);
x.domain([0, root.value]).nice();
down(root, 0);
});
I have been able to pass the embedded JSON to an object after following this thread:
Best practice for embedding arbitrary JSON in the DOM?
How can I now successfully pass this object to the D3 bar chart?
Parsing the embedded JSON object was the hard part, so you've basically got this one figured out. Once you have the embedded JSON parsed and passed to an Object, you can just start using that Object.
Building off of your example, say you had this JSON data embedded in your page:
<script type="application/json" id="data">
{"name": "flare", "children":[{"name": "thing1", ... }]}
</script>
Then instead of using
d3.json("data/file.json", function(root) {
...
}
just extract the body of the function you were using, and load the JSON object at the top:
var root = JSON.parse(document.getElementById('data').innerHTML);
hierarchy.nodes(root);
x.domain([0, root.value]).nice();
down(root, 0);
...
The method described in the question you've linked to will work. Just call the variable whatever you're using in your D3 code, e.g.
var root = JSON.parse(document.getElementById('data').innerHTML);
I am using struts 2 and velocity templates to generate JSON response.
Now the catch is the response is not generated using some velocity JSON plugin
it's just a String that comes out once velocity is done with its parsing and rendering of
response, and on client side I do eval to get the response from string to JSON.
What I really need is some solution on velocity's or struts' side where, once the result is
generated by velocity, the framework should call my API where I can convert the response output of vm file into JSON using my own logic. How do achieve this?
For example:
On browser using JavaScript I have designed a tree widget that I use for displaying comments in tree structure.
Say user clicks on comments button.
My UI widget will fire an AJAX to get data for comments.
This request is intercepted by STRUTS 2 framework.
It will call, say, getComments() action API and will populate an arrayList with comment object say cmt.
Now the response is handled by a velocity template(*.vm).
Now in vm I am writing code like this:
{ "CommentsData" : [
#set($sep="")
#foreach($c in $cmt)
$sep
{
"commentText" : $c.getText()
}
#set($sep=",")
#end
}
Now the final response may turn out like this:
{ "CommentsData" : [
{
"commentText" : "This is comment 1"
},
{
"commentText" : "This is comment 2"
},
{
"commentText" : "This is comment 3"
},
{
"commentText" : "This is comment 4"
}`
]
}
Now this may look like JSON, but its not strict JSON; I mean if I miss
some , somewhere then on client side in JavaScript my eval might fail or JSON.parse()
will fail, but on velocity template I have now clue if JSON is malformed.
So once the above velocity template is generated I need some control, where I can write some Java code to do some validations on the response.
I see that my approach to use velocity template to generate JSON output (actully a String that looks like JSON) may be wrong. But still I need to handle the response of every velocity template I have written.
Not sure how you are using velocity. We don't use velocity when outputting JSON; we just create a JSON convertible object and output it directly from controllers using response.write(jsonObject.toJson()). This way, proper JSON is always generated.