0

I'm having an issue with JSONPath work. I have two very similar json objects that I am trying to get values from.

Essentially the objects roughly look like this:

Object1: {Company: {Organisation: {Official Name: "Name"}}
jsonpath1: Company..Organisation..Official Name
Object2: {Company: {Organisation:"Name"}}
jsonpath2: Company..Organisation

My issue is that I need both of these paths running. For Object2, this causes no issue as the first jsonpath doesn't return anything.

For object1 however, jsonpath 1 returns the required value. However, for this record jsonpath2 also returns the value Object object.

Is there any way to stop this from happening? I require both json paths. They both return the name of the company but unfortunately the data structure has changed - hence the issue

peak
  • 105,803
  • 17
  • 152
  • 177
nimgwfc
  • 1,294
  • 1
  • 12
  • 30

1 Answers1

1

If you're open to using , then a solution to the problem of writing a query that will retrieve the company name is very simple:

.Company.Organisation | if type == "string" then . else ."Official Name" end

Example

For example, if company.json contains the lines:

{"Company": {"Organisation": {"Official Name": "Name1"}}}
{"Company": {"Organisation": "Name2"}}

then the result of running

jq '.Company.Organisation | if type == "string" then . else ."Official Name" end' company.json

would be:

"Name1"
"Name2"

(If you want the names without the outer quotation marks, you could run jq with the -r command-line option.)

peak
  • 105,803
  • 17
  • 152
  • 177