O
O
ojiekcahdp2021-01-09 22:04:55
JavaScript
ojiekcahdp, 2021-01-09 22:04:55

How to find a string and the value of that string in JSON?

I want to check the JSON file, find the string "nick" for all users there, and do this:
( ) that is, if one of the participants has nick = high, then nothing was done, how to find the value nick = from the entire JSON hey, or can you make it easier? Here is my JSON:if(nick = "хай") return

{
    "id": 124124,
    "firstname": "Районный",
    "lastname": "Прокурор",
    "warns": 0,
    "role": 11,
    "flip": 0,
    "rank": "Участник",
    "ban": false,
    "isBanned": "Нет",
    "tempban": 0,
    "mute": 0,
    "mutesleft": 0,
    "violations": 0,
    "botmute": 0,
    "nick": "хай"
  },
  {
    "id": 123123,
    "firstname": "Кто",
    "lastname": "Никто",
    "warns": 0,
    "role": 11,
    "flip": 0,
    "rank": "Участник",
    "ban": false,
    "isBanned": "Нет",
    "tempban": 0,
    "mute": 0,
    "mutesleft": 0,
    "violations": 0,
    "botmute": 0
    "nick": "пока"
  },
  {
    "id": 125125,
    "firstname": "Крутой",
    "lastname": "Поц",
    "warns": 0,
    "role": 1,
    "flip": 0,
    "rank": "Участник",
    "ban": false,
    "isBanned": "Нет",
    "tempban": 0,
    "mute": 0,
    "mutesleft": 0,
    "violations": 0
    "nick": "привет"
  }

Answer the question

In order to leave comments, you need to log in

2 answer(s)
T
Tim, 2021-01-09
@ojiekcahdp

const json = `[{"id":124124,"firstname":"Районный","lastname":"Прокурор","warns":0,"role":11,"flip":0,"rank":"Участник","ban":false,"isBanned":"Нет","tempban":0,"mute":0,"mutesleft":0,"violations":0,"botmute":0,"nick":"хай"},{"id":123123,"firstname":"Кто","lastname":"Никто","warns":0,"role":11,"flip":0,"rank":"Участник","ban":false,"isBanned":"Нет","tempban":0,"mute":0,"mutesleft":0,"violations":0,"botmute":0,"nick":"пока"},{"id":125125,"firstname":"Крутой","lastname":"Поц","warns":0,"role":1,"flip":0,"rank":"Участник","ban":false,"isBanned":"Нет","tempban":0,"mute":0,"mutesleft":0,"violations":0,"nick":"привет"}]`;

const data = JSON.parse(json);

function findNick(arr, nick) {
  const res = arr.find(i => i.nick == nick);
  if (res) return;
  return arr;
}
console.log(findNick(data, 'хай'));

A
Andrey Ezhgurov, 2021-01-09
@eandr_67

It's not JSON - it's missing the enclosing '[' and ']'.
We simply turn the string containing the JSON into a JavaScript array and loop through that array:

for (let e of JSON.parse('здесь должен быть JSON-массив')) {
  if (e.nick == 'хай') { return; }
}

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question