4

I'm beginner on programming. I've studied Stack Overflow and W3schools, and made my little project just for learning and improving.

I have a question, my program is working as it should but the problem is I'm not sure (have doubts) is the json file I made real json or JavaScript object?

One says it is and one says it's not, if it's not real json how to change it into real json because I can't figure it out.

I have three groups inside every group is 4 people and those people are the same in all 3 groups but just different numbers (credits or votes whatever), and I have a json file (I think it is json) named 'values.json'.

Here are codes:

  <!DOCTYPE html>
    <html lang="en">

    <head>
      <meta charset="utf-8">
      <meta name="viewport" content="width=device-width, initial-scale=1">
      <script type="text/javascript" src="values.json"></script>
    <style>
    * {
        box-sizing: border-box;
    	   box-sizing: border-box;
       -webkit-box-sizing
       -moz-box-sizing: border-box;
    }

    .oee {
      float:left;
      height: 550px;
      width: 100%;
      display: inline-block;
    }

    .gauge {
      height: 250px;
      display: inline-block;
      width: 100%;
    }
     
    h1 { 
      float:left;  
    }

    body {   
      margin: 100px auto;  
      text-align: center; 
    }

    @media only screen and (orientation: landscape) {
    .gauge {
      width: 30%; 
    }

    .oee{width: 50%;
      margin-left: -132px;
    }
    }
      </style>
    </head>
    <body >
    <h1>people votes</h1>
     <div class="all">
         <div id="ww1" class="oee"></div>
        <div id="ww2" class="gauge" data-value=valuesparsed['Pekka']></div><br>
    	<div id="ww3" class="gauge"></div><br>
        <div id="ww4" class="gauge"></div>
      </div>    
      <script src="raphael-2.1.4.min.js"></script>
      <script src="justgage.js"></script>
      <script>
      document.addEventListener("DOMContentLoaded", function(event) {
        var valuesparsed = JSON.parse(values2)

        var dflt = {
          min: 0,
          max: 100,
       //   donut: true,
          gaugeWidthScale: 1.1,
          counter: true,
          hideInnerShadow: true
        }

        var ww1 = new JustGage({
          id: 'ww1',
          value: valuesparsed['Laura'],
          title: 'Laura ',
          defaults: dflt
        });

        var ww2 = new JustGage({
          id: 'ww2',
          title: 'Pekka',
          defaults: dflt
        });
    	
    	    var ww3 = new JustGage({
          id: 'ww3',
          value: valuesparsed['Jussi'],
          title: 'Jussi',
          defaults: dflt
        });
    	
    	    var ww4 = new JustGage({
          id: 'ww4',
          value: valuesparsed['Kalle'],
          title: 'Kalle',
          defaults: dflt
        });

      });
      
      </script>
    </body>
    </html>

values.json

    values1= '{"Laura" : 45, "Pekka" : 89, "Jussi" : 35, "Kalle" : 25}';
    values2= '{"Laura" : 75, "Pekka" : 59, "Jussi" : 85, "Kalle" : 95}';
    values3= '{"Laura" : 55, "Pekka" : 15, "Jussi" : 45, "Kalle" : 67}';

1
  • at first sight i think your .json content is in a bad format, use this tool to check what's wrong and fix the formatting Commented Nov 30, 2018 at 14:30

4 Answers 4

2

The file you call values.json is not JSON, but a script in the JavaScript language. Such a script you can indeed include and run via the script tag.

If however you want to have JSON format for your data, and you want to have it loaded from a file into your other JavaScript code, then proceed like this:

  1. Put JSON in your file (no variable names, no assignments, no trailing semi-colon, just JSON) -- it can only be one data structure, so let's use an array:

    [{"Laura" : 45, "Pekka" : 89, "Jussi" : 35, "Kalle" : 25},
     {"Laura" : 75, "Pekka" : 59, "Jussi" : 85, "Kalle" : 95},
     {"Laura" : 55, "Pekka" : 15, "Jussi" : 45, "Kalle" : 67}]
    
  2. Remove the script src= tag.

  3. Mark the DOMContentLoaded callback function as asynchronous:

    document.addEventListener("DOMContentLoaded", async function(event) {
    //                                            ^^^^^
    
  4. Add code within that callback to load and parse the JSON into a variable arr:

    var response = await fetch("values.json");
    var arr = await response.json();
    var valuesparsed = arr[1]; // choose here which of the three you want to work with
    
    // Rest of your code comes here...
    
Sign up to request clarification or add additional context in comments.

4 Comments

thanks for right answer, i have one question, why you didnt use JSON.parse(), for parsing ? are there many ways of 'parsing' ?
I didn't use it, because a fetch response provides a method to do that. Otherwise you would have to first retrieve the text from the response with await response.text() and then call JSON.parse on it, which represents one step more.
can i ask why you used fetch and not ajax, or is it not needed ?
Fetch is doing ajax. Maybe you are thinking of jQuery's implementation?
2

Your value.json

values1= '{"Laura" : 45, "Pekka" : 89, "Jussi" : 35, "Kalle" : 25}';
values2= '{"Laura" : 75, "Pekka" : 59, "Jussi" : 85, "Kalle" : 95}';
values3= '{"Laura" : 55, "Pekka" : 15, "Jussi" : 45, "Kalle" : 67}';

is not really JSON.

JSON starts with either

{

An object.

or

[

An Array.

and ends with the same depending on their start.

An examaple would be

{"Laura" : 45, "Pekka" : 89, "Jussi" : 35, "Kalle" : 25}

In Your scenario you would like to have a JSON array that will hold your objects, something like this:

[{
        "Laura": 45,
        "Pekka": 89,
        "Jussi": 35,
        "Kalle": 25
    },
    {
        "Laura": 75,
        "Pekka": 59,
        "Jussi": 85,
        "Kalle": 95
    },
    {
        "Laura": 55,
        "Pekka": 15,
        "Jussi": 45,
        "Kalle": 67
    }
]

3 Comments

first i did it like this but didnt know how to connect each group to each people, got one working and another didnt ...
0, "Hello", null are all valid JSON representations, in addition to objects and arrays.
how to make it work like it is now but with real json ?
0

The content of values.json is a JavaScript program which assigns three string literals to three global variables.

The value of each of those strings is a JSON text.

If you wanted to have just JSON in that file, then you would need either:

3 separate URLs each containing a JSON text like:

{"Laura" : 45, "Pekka" : 89, "Jussi" : 35, "Kalle" : 25}

or 1 URL containing an array of objects:

[
  {"Laura" : 45, "Pekka" : 89, "Jussi" : 35, "Kalle" : 25},
  {"Laura" : 75, "Pekka" : 59, "Jussi" : 85, "Kalle" : 95},
  {"Laura" : 55, "Pekka" : 15, "Jussi" : 45, "Kalle" : 67}
]

Then you would need to load the JSON data using a different mechanism (it JSON is not JavaScript, you cannot load it using <script>) such as the fetch API.

async function process_json() {

    const response = await fetch('your_json.json');
    const data = response.json();
    console.log(data);

}

2 Comments

as it is now working, but how to make it work with real json ?
and for selexting json text i need some kind of looping ? could you give and example of that also, or it could be done without loop ?
0

So, @walee, just to emphasise on the existing answers, I've created a plunker to sort of show the difference between JSON and JS objects.

In a nutshell, I've extracted your values.json to real json:-

[
    {"Laura" : 45, "Pekka" : 89, "Jussi" : 35, "Kalle" : 25}
    ...
    ...
]

And Js:

const values1 = {"Laura": 45, "Pekka": 89, "Jussi": 35, "Kalle": 25},
    ...

In the plunker, I've demonstrated fetching the json file using the Fetch API, but fill free to use any HTTP library out there.

4 Comments

now it is working and doesnt need any loops, but when using json array do i need some kind of looping through it ? in order to parse values ?
Not really, you don't always need loops. You can still access array elements via keys e.g arrayValues[0] to get the first object and arrayValues[n-1] for the last object (where n is the length of your array)
The plunker does not correctly show how to process the values from the JSON file. The code runs correctly only because you also define the values inside the script. But once you take that out and only rely on the JSON, it doesn't work.
@trincot, how are script defined variables related to JSON buddy?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.