0

For example, I have a JSON file called Stores.json that has lots of numbers like 1142,1234,1890, etc and each one has an address associated with it. It looks something like this but there are thousands of objects:

    {
      "1142": {
        "Name": "P. Sherman",
        "Address": "42 Wallaby Way, Sydney",
      }
    }

I have already looked at this answer: https://stackoverflow.com/a/24378510 But I am still confused about how to read a file based on a string, such as "1142", because I don't know what line the number is on if there are many lines.

I tried:

var mydata = JSON.parse(data**[this is Stores.json]**);
addr = mydata["1142"];

Maybe I am just confusing JavaScript with PHP? PHP code would work but I would like the JavaScript version.

EDIT: Assume that there are many objects in the file, I need to be able to select an object using a number. Basically none of the JSON is written in the Javascript Code.

Community
  • 1
  • 1
Andrey
  • 44
  • 1
  • 11

4 Answers4

2

Try this:

function getJsonObj(path, func)
{
    var xhr = new XMLHttpRequest();

    xhr.open('GET', path, true);
    xhr.onload = function()
    {
        var jso = JSON.parse(this.response);
        var key = Object.keys(jso)[0];
        var obj = jso[key];

        func(key,obj);
    }

    xhr.send(null);
}

getJsonObj('path/to/file.json', function(key, obj)
{
    // do stuff
});

Using the above, you do not need to know what the "number" is as it assumes that it's the first object in the response JSON.

The function accepts a "call-back" function as second argument, so it's asynchronous (non-blocking); which returns the "number" (key) and the number's data (obj).

This will take care of "white-space" also, where if you read it line-by-line, your "number" may be on a different line when dealing with another json-data-output api in the future.


Edit:

If the above code does not work exactly as it is, try replacing the xhr.onload part with this:

xhr.onreadystatechange = function()
{
    if ((xhr.readyState == 4) && (xhr.status == 200))
    {
        // the rest here
    }
}

Update

If you don't know what exactly is in the file, and need to filter out only the JSON part, then you can do something like this:

// ...
var txt = this.responseText;
var jso = JSON.parse(txt.substr(txt.indexOf('{'), txt.lastIndexOf('}')));
// ...

Then, if the parsed JSON is an array (or list of objects), you can iterate through them with something like this:

jso.forEach
(
    function(item, indx)
    {
        if (!(typeof item == 'object'))
        { return; }

        var key = Object.keys(item)[0]; // your object "number"
        var obj = item[key];            // your object number's value

        if (isNaN(key * 1))  // checks if the key is a number
        { return; }

        // continue here ...
    }
);

Use the code alterations above as you see fit in the right places accordingly.

  • 1
    Thanks, but that Object is one of many in the file, is there a way to load it from the file, without knowing what the file has in it? (basically none of the JSON is in the code.) – Andrey Apr 12 '16 at 01:40
  • If the file contains only JSON, and those objects are a list (array) of objects, then you can just use it accordingly, as a list of objects. I'm not sure what you want to accomplish here, but if I know more I can edit the answer accordingly. –  Apr 12 '16 at 01:45
  • You may need to format the JSON source (text from file) before parsing it, I don't know, which-ever it is; the more you elaborate on the problem and the desired outcome, -the better answers you will get related to your specific needs. –  Apr 12 '16 at 01:55
  • 1
    Edited acordingly. – Andrey Apr 12 '16 at 01:58
  • @AndreyNazarchuk :: i've added a check for numbered keys only. Remember to choose any answer that suits your needs, even if you have to write an answer yourself ;) –  Apr 12 '16 at 02:33
  • 1
    how would I find just the store number I am looking for? basically I need this code to find an address for a certain store number from a json file 1000s of lines long. – Andrey Apr 12 '16 at 02:37
  • @AndreyNazarchuk :: I'm writing a new answer which will contain the edits and updates with "search" functionality as needed. –  Apr 12 '16 at 02:40
1

JSON.parse takes a string

var data = "{\"1142\":{\"Name\":\"P. Sherman\",\"Address\":\"42 Wallaby Way, Sydney\"}}";
var mydata = JSON.parse(data);
console.dir(mydata["1142"]);

If your data is already in object notation, don't parse it.

var data = {
  "1142": {
    "Name": "P. Sherman",
    "Address": "42 Wallaby Way, Sydney"
  }
};
console.dir(data["1142"]);
Will
  • 3,201
  • 1
  • 19
  • 17
  • Thanks, but that Object is one of many in the file, is there a way to load it from the file, without knowing what the file has in it? (basically none of the JSON is in the code.) – Andrey Apr 12 '16 at 01:40
1
var data = {
  "1142": {
    "Name" : "Sample Name",
    "Address" : "My address",
  }
};

Firstly, the variable data has already been parsed, therefore

var mydata = JSON.parse(data);

is not needed. You can access the variables in this form:

var x = data['1142'];
alert(x.Name);
alert(x.Address);
cookies
  • 323
  • 1
  • 9
  • 1
    Thanks, but that Object is one of many in the file, is there a way to load it from the file, without knowing what the file has in it? (basically none of the JSON is in the code.) – Andrey Apr 12 '16 at 01:40
  • $.each(result, function (key, object) { console.log("Name:", object.Name, "Address:", object.Address);}); – cookies Apr 12 '16 at 02:07
0

Based on the comments, here is a more appropriate answer to your specific needs:

function findStore(numb, file, func)
{
    var xhr = new XMLHttpRequest();

    xhr.open('GET', path, true);
    xhr.onreadystatechange = function()
    {
        if ((xhr.readyState == 4) && (xhr.status == 200))
        {
            var txt, jso;

            txt = this.responseText;
            jso = JSON.parse(txt.substr(txt.indexOf('{'), txt.lastIndexOf('}')));

            jso.forEach
            (
                function(item, indx)
                {
                    if (!(typeof item == 'object'))
                    { return; }

                    var key = Object.keys(item)[0];
                    var obj = item[key];

                    if ((key *1) == (numb *1))
                    { func(obj); }
                }
            );
        }
    }
    xhr.send(null);
}

You can use the function above like this:

findStore(1234, 'path/to/file', function(store)
{
    // console.log(store);
});
  • 1
    obj is the json object? so If I do `var addr = obj.address;` it will be the address? – Andrey Apr 12 '16 at 04:56
  • @AndreyNazarchuk :: yes ;) –  Apr 12 '16 at 04:58
  • Only a pleasure. Remember to "up-vote" answers, questions and comments that are useful as it is appreciated and motivates others to answer your questions, or provide useful input. –  Apr 12 '16 at 05:03
  • haha i wish it would let me... Ill be sure to come back and do it as soon as i have 15 points – Andrey Apr 12 '16 at 05:06
  • It has an error: SyntaxError: Unexpected end of input xhr.onreadystatechange (JSON.parse line) – Andrey Apr 16 '16 at 03:39