使用 jq 连接相邻对象的值

Concatenate values from adjacent objects using jq

如果给定值匹配,我想连接相邻对象的值。

正如您在下面看到的,路径中带有 ParagraphSpan 的文本字段在对象之间拆分,而不是自包含的 P。

{
  "Path": "//Document/P[5]",
  "Text": "WELLNESS AS A HEALTH GOAL "
},
{
  "Path": "//Document/P[6]/ParagraphSpan",
  "Text": "Although we use the words health and wellness interchangeably, they differ in two important ways. Health can be determined "
},
{
  "Path": "//Document/P[6]/ParagraphSpan[2]",
  "Text": "or influenced by factors beyond your control, such as your genes, age, and family history."
},
{
  "Path": "//Document/P[7]",
  "Text": "Dimensions of Wellness "
},
{
  "Path": "//Document/P[8]",
  "Text": "The process of achieving wellness is continual and dynamic, involving change and growth. "
},
{
  "Path": "//Document/P[9]",
  "Text": "Your physical wellness includes not just your body’s overall condition and the absence of disease "
}

是否可以在 ParagraphSpan 下合并文本?

"Path": "//Document/P[6]/ParagraphSpan",
"Text": "Although we use the words health and wellness interchangeably, they differ in two important ways. Health can be determined or influenced by factors beyond your control, such as your genes, age, and family history.  ",

如果您的输入包含一个 JSON 数组和如图所示的 {Path, Text} 对象,那么您可以通过以下方式实现您描述的合并:

reduce .[] as $x (null;
  if $x|.Path|contains("/ParagraphSpan[")
  then .[-1].Text += $x.Text
  else . + [$x] end) 

在实践中,您可能希望添加一些检查,或者对合并对象施加更严格的要求,或者确保正确完成文本合并。