How to store json file in object property


#1

Hi i have json file with all users and users details. Now i want something like this

function User() {};
 $.getJSON('/allusers.json', function(request){

      Users.names = request.names;
      
    });

#2

Using a simple object to hold the information works well.

var users = {};

 $.getJSON('/allusers.json', function(request) {
    users.names = request.names;
 });

Another way of doing the above using composition techniques is:

var users = {};

function getNames(response) {
    return response.names;
}
function storeNames(names) {
    users.names = names;
}
 $.getJSON('/allusers.json')
    .pipe(getNames)
    .then(storeNames);

Or, if you like doing things inline:

const users = {};

 $.getJSON('/allusers.json')
    .pipe(response => response.names)
    .then(names => users.names = names);

Edit:

getNames changed to response

#3

I should make sure that the code I gave works properly, so this is a good opportunity to go through how to test server-side code from a local machine.

Setting up a local server with npm

We can use serve to easily create a test server, so first we need to init a new node project. The command-line is a good place to do this from.

If you don't have node or npm, instructions are found at Installing node and updating npm

Here I'll use npm init -y to create a temporary project, where -y says to provide default answers for all of the questions.

C:\Users\paulm\sitepoint>mkdir store json-names-in-object

C:\Users\paulm\sitepoint>cd store-json-names-in-object

C:\Users\paulm\sitepoint\store-json-names-in-object>npm init -y
Wrote to C:\Users\paulm\sitepoint\store-json-names-in-object\package.json:

{
  "name": "store-json-names-in-object",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  "keywords": [],
  "author": "",
  "license": "ISC"
}

C:\Users\paulm\sitepoint\store-json-names-in-object>

We can then install serve, which will give lots of details about the installation that we don't need to study.

C:\Users\paulm\sitepoint\store-json-names-in-object>npm install serve
npm WARN deprecated chalk@2.0.1: Please upgrade to Chalk 2.1.0 - template literals in this version (2.0.1) are quite buggy.
store-json-names-in-object@1.0.0 C:\Users\paulm\sitepoint\store-json-names-in-object
`-- serve@6.2.0
  +-- args@3.0.4
  | +-- camelcase@4.1.0
  | +-- chalk@2.0.1

...

    |   |   `-- strip-json-comments@2.0.1
    |   `-- registry-url@3.1.0
    +-- semver-diff@2.1.0
    | `-- semver@5.4.1
    `-- xdg-basedir@3.0.0

npm WARN store-json-names-in-object@1.0.0 No description
npm WARN store-json-names-in-object@1.0.0 No repository field.

C:\Users\paulm\sitepoint\store-json-names-in-object>

Those warnings are useful when doing a real project, but I'm okay with ignoring them on this brief test.

We can then add serve to package.json in our scripts area, and we'll be ready to start.

package.json

  ...
  "scripts": {
    "start": "serve",
    "test": "echo \"Error: no test specified\" && exit 1"
  },
  ...

We can now use the command npm start to run serve, and our local server will be ready.

C:\Users\paulm\sitepoint\store-json-names-in-object>npm start

> store-json-names-in-object@1.0.0 start C:\Users\paulm\sitepoint\store-json-names-in-object
> serve


   ┌──────────────────────────────────────────────────┐
   │                                                  │
   │   Serving!                                       │
   │                                                  │
   │   - Local:            http://localhost:5000      │
   │   - On Your Network:  http://192.168.1.57:5000   │
   │                                                  │
   │   Copied local address to clipboard!             │
   │                                                  │
   └──────────────────────────────────────────────────┘

Navigating our web browser to http://localhost:5000 now shows the content of our project.

Preparing for the first code sample test

I can now create an index.html file, for the purpose of testing the json code from my previous post. The <pre> result section is where I plan to show the contents of the users variable.

<!DOCTYPE html>
<html>
<head>
    <title>Store JSON names in an object</title>
</head>
<body>
  <h1>Store JSON names in an object</h1>
  <pre id"result"></pre>
</body>
</html>

Reloading the webpage should now load that index.html file, with the appropriate title and heading.

We are going to need a JSON file for this test. I see that it's called allusers.json so I'll make a sample user file, using randomly generated fake names to generate some test user data.

allusers.json

{
    "names": [
        "Austin West",
        "Raymond Ray",
        "Jessica Hall"

    ],
    "users": [
            {
            "name": "Austin West",
            "gender": "Male",
            "region": "United States",
            "phone": "(642) 160 5424",
            "birthday": "02/04/1991",
            "email": "austin_west@example.com",
            "username": "austinwest",
            "password": "West91$(]",
        },
        {
            "name": "Raymond Ray",
            "gender": "Male",
            "region": "United States",
            "phone": "(532) 798 8735",
            "birthday": "30/12/1983",
            "email": "raymondray@example.com",
            "username": "raymondray",
            "password": "Ray83^*"
        },
        {
            "name": "Jessica Hall",
            "gender": "Female",
            "region": "United States",
            "phone": "(807) 124 5175",
            "birthday": "19/01/1993",
            "email": "jessica_hall@example.com",
            "username": "jessicahall",
            "password": "Hall93{*"
        }
    ]
}

I've included other user data there too, because, well you never know how much information might be wanted for later testing.

Testing the first code sample

I can now create getuserdata.js and test the first sample code:

var users = {};

 $.getJSON('/allusers.json', function(request) {
     users.names = request.names;
     document.getElementById("result").innerHTML = JSON.stringify(users, undefined, 4);
 });

Running that and we get a $ not found error. Oh yes, and jQuery will be wanted for the test too. We can load jQuery from a CDN and the script from the main index.html file.

  ...
  <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
  <script src="getuserdata.js"></script>
</body>
</html>

And the code runs, but the console doesn't show anything. Why? It's as if the function didn't run at all.

The $.getJSON() page says "As of jQuery 1.4, if the JSON file contains a syntax error, the request will usually fail silently." so time to check the test JSON file from earlier., with JSONLint

The linting page tells us:

Error: Parse error on line 16:
...rd": "West91$(]",        },      {           "name": "R
----------------------^
Expecting 'STRING', got '}'

I had left an accidental trailing comma after the password field. Removing that trailing comma from the password, which is the last item in the object, gives us:

           ...
            "password": "West91$(]"
        },
        {
            "name": "Raymond Ray",
            ...

Running the page now, I am correctly shown the JSON list of names on the web page.
That's the first sample code tested. Time to move on to the next code.

Testing the second code sample

The code in getuserdata.js can all be replaced with the following:

getuserdata.js

var users = {};

function getNames(response) {
    return response.names;
}
function storeNames(names) {
    users.names = names;
}
function showUsersResult() {
    document.getElementById("result").innerHTML = JSON.stringify(users, undefined, 4);
}

 $.getJSON('/allusers.json')
    .pipe(getNames)
    .then(storeNames)
    .then(showUsersResult);

Refreshing the page and the same list of users is showing. This is where a mental conflict occurs. Did it run perfectly? It is more likely that I hadn't saved the new code, or that the server is running a cached version of the previous code.

Loading up the network request info from the webpage though does show that the new updated file is being run, so this updated code runs perfectly.

Testing the last code sample

I can now test the last of the sample code that I provided, which is:

const users = {};

 $.getJSON('/allusers.json')
    .pipe(getNames => response.names)
    .then(names => users.names = names)
    .then(() => result.innerHTML = JSON.stringify(users, undefined, 4));

and refreshing the webpage doesn't show any data. Why? Oh, the response isn't found.

getNames need to be renamed to response.

const users = {};

 $.getJSON('/allusers.json')
    .pipe(response => response.names)
    .then(names => users.names = names)
    .then(() => result.innerHTML = JSON.stringify(users, undefined, 4));

And now that I know that the original code that I posted has an error in it, I can go back to that earlier post and make a correction, with an edit note to indicate what the change was, and this post to help inform people that might have already seen the previous post too.

That brings us to an end on how to test server code on your local machine. I hope that it's been somewhat successful in helping to demonstrate some of the easy techniques that can be used to help you out.

Edit:

Added some headings, and info on installing node/npm

#4

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.