1

At first, my question might sound unclear. I'm new to JSON, but let me explain.

I have the following JSON file (which I can't modify):

{
  "jsonexample": [
    {
      "Name": "Test1",
      "Text": "This is test 1.",
      "TestNumber": 1
    },
    {
      "Name": "Test2",
      "Text": "This is test 2.",
      "TestNumber": 2
    }
  ]
}

How can I find TestNumber based on Name?

This code doesn't work:

console.log(jsonexample.Name.Test1.TestNumber);

I thought it would give me 1 from the Test1 name data.

What would be the code which would be able to get the TestNumber data by giving the Name information only?


Edit: How could I make this work for a JSON WebPage : an API ?

4 Answers4

1

You can loop through the array and do something like if(object.Name = name){ return object.TestNumber}, as the below demo shows.

(This assumes your source is actually a JSON string that you need to parse. If it's already a JavaScript object, you can skip that step.)

const
  myData = JSON.parse(getDataArrayAsJson()),
  num = getNumberByName(myData, "Test1");
console.log(num);


function getNumberByName(data, name){
  for(let object of data){
    if(object.Name = name){ return object.TestNumber}
  }
}

function getDataArrayAsJson(){
 return JSON.stringify ([
    { Name : "Test1", Text: "This is test 1.", TestNumber : 1 },
    { Name : "Test2", Text : "This is test 2.", TestNumber : 2 }
  ]);
}
Cat
  • 4,016
  • 2
  • 7
  • 17
  • Could I make this work for a JSON file on a webPage ? – SparklingIsGood Jul 26 '20 at 19:33
  • Sure. If you read the JSON string from a file and store it in a variable called `dataArray`, then probably the only change you'd need to make to the demo code is to replace `getDataArrayAsJson()` with `dataArray`. – Cat Jul 26 '20 at 19:42
  • Could you edit your answer to get the two demo codes? Thanks – SparklingIsGood Jul 26 '20 at 19:45
  • I'm not sure what you mean by "get the two demo codes". (And I can't get your JSON string because I don't have access to your server.) – Cat Jul 26 '20 at 19:53
  • Let me clarify what I meant, could you include a demo code for the way to get the JSON file from a webPage (API) ? – SparklingIsGood Jul 26 '20 at 19:55
  • That's kind of a separate question, but what API are you using? If I can access it without a key, I'd be happy to take a look. – Cat Jul 26 '20 at 20:06
  • Yes, it is free. It is a CoronaVirus API. I would like to give the country and the code to return any country information I would like to show. Here is the link: https://api.covid19api.com/summary – SparklingIsGood Jul 26 '20 at 20:08
  • The documentation (https://documenter.getpostman.com/view/10808728/SzS8rjbc?version=latest#00030720-fae3-4c72-8aea-ad01ba17adf8) for the endpoint url you provided says you'd specify a `GET` `xmlHTTPRequest` to send there (like **`myRequest.open("GET", "api.covid19api.com/summary");`**). If you're trying to learn how to send an HTTP request at all, I think that's definitely outside the scope of this question, but two great resources are **MDN** https://developer.mozilla.org/en-US/docs/Web/API/XMLHttpRequest/Using_XMLHttpRequest and javascript.info https://javascript.info/xmlhttprequest#summary – Cat Jul 26 '20 at 20:53
1

Two things:

  1. if you have a string {"jsonexample":...} and parse it into something, at the end you will have have something.jsonexample (and not jsonexample)
  2. something.jsonexample will be an array, it will not have something.jsonexample.Test1, but something.jsonexample[<index>]. Test1 is value of Name inside, so even if you know that the index is 0, Test1 is going to be a result of something.jsonexample[0].Name and something.jsonexample[0].Test1 will not exist

How can I find TestNumber based on Name?

Exactly that way, using find:

var jsonStringFromWeb = `{
  "jsonexample": [
    {
      "Name": "Test1",
      "Text": "This is test 1.",
      "TestNumber": 1
    },
    {
      "Name": "Test2",
      "Text": "This is test 2.",
      "TestNumber": 2
    }
  ]
}`;

var parsedJson = JSON.parse(jsonStringFromWeb);
var neededObject = parsedJson.jsonexample.find(item => item.Name==="Test1");
console.log(neededObject.TestNumber);
tevemadar
  • 11,284
  • 3
  • 17
  • 44
0

If you have a valid JSON string, you can convert it to JavaScript object. [] indicates an array. {} indicates an object.

So let's covert your string to a valid JSON:

{
"jsonexample" : [
  {
     "Name" : "Test1",
     "Text": "This is test 1.",
     "TestNumber" : 1
  },
  {
     "Name" : "Test2",
     "Text" : "This is test 2.",
     "TestNumber" : 2
  }
]
}

(it's object with one property containing an array of objects)

Then in javascript you can convert that string using JSON.parse:

var json = JSON.parse(theJsonFromAbove);
alert(json.jsonexample[0].Name); // Test1
alert(json.jsonexample[0].Text); // This is test 1.
alert(json.jsonexample[0].TestNumber); // 2
user3058763
  • 339
  • 2
  • 13
-1

You have some invalid JSON, which I may have cleaned up below.

var j = {
  jsonexample: [{
    Name: "Test1",
    Text: "This is test 1.",
    TestNumber: 1
  }, {
    Name: "Test2",
    Text: "This is test 2.",
    TestNumber: 2
  }]
};

console.log(j.jsonexample[0].Name);
mankowitz
  • 1,602
  • 1
  • 13
  • 27
  • 1
    Who said the needed value is in first object? – Lemmy Jul 26 '20 at 19:26
  • JSON actually requires double quotes around the keys, so this isn't quite valid yet. (And Lemmy is correct that you can totally get away with supplying an array as the top-level structure for your JSON -- Technically, you could even supply just a primitive value, but that would usually not be particularly useful.) – Cat Jul 26 '20 at 19:35