PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Saturday, July 23, 2022

[FIXED] How to extract fields from a JSON file

 July 23, 2022     arrays, jq, json     No comments   

Issue

I am new to coding in general but I'm trying to shift my attention to learning JAVA, JSON and JQ.

Having said this, I have created the following JSON file:

    {
"users": 
[
    {"Firstname": "Rolo",
        "Lastname": "Car",
          "Hobbies": ["Metalcore", "concerts", "beach"],
        "friends": [
            {"Firstname":"Nitsuki",
                "Lastname": "Saixx"
            },
            {"Firstname":"Confesora",
                "Lastname": "Kahlan"
            }
        ]
    },
    {"Firstname":"Ernest",
        "Lastname": "Vast"
        "Hobbies": ["Barista", "Strategy games", "RPG games"],
        "friends": [
            {"Firstname":"Diana",
                "Lastname": "Vast"
            },
            {"Firstname":"Pat",
                "Lastname": "Vanberg"
            }
        ]
    },
    {"Firstname":"Juls",
        "Lastname": "Santana",
        "Hobbies": ["Sew", "Watch Gossip shows", "Foodie"],
        "friends": [
            {"Firstname":"Laura",
                "Lastname": "Reed"
            },
            {"Firstname":"Sandy",
                "Lastname": "Vast"
            }
        ]
    }

I am trying to get the following results:

"Rolo"
"Ernest"
"Juls"

When I enter the following JQ command

cat file.json | jq "[].Firstname"

I get the error

jq: error (at <stdin>:56): Cannot index array with string "Firstname"

Any suggestions on what I could be doing wrong? Thank you so much for your time!


Solution

Couple of issues in the json you posted first:

  • You need a comma after "Lastname": "Vast"
  • You need to complete the object by closing users array (add a ] at the end), and then closing the entire object (adding a } at the end)

This command then works:

cat test.json | jq '.users[].Firstname'

You need to tell jq which array you want to get the Firstname values from (the users array, in your case), as the initial input is an object, and so cannot be traversed via [] not the collection containing values with a Firstname property.



Answered By - anqit
Answer Checked By - Terry (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing