使用结构语言从json字符串中提取数据 [英] Extract data from a json string with a structure language

查看:55
本文介绍了使用结构语言从json字符串中提取数据的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我不知道这件事是否存在或最佳实践是否已经存在.

I don't know if this thing exists or if a best practices already exists.

我有一个json字符串,我想知道是否可以使用sql中的查询字符串从此json提取数据.

I have a json string and I would like to know if it's possible to extract data from this json using a query string like in sql.

带有此json的示例:

Example with this json:

    [
  {
    "user": [
      {
        "id": 1,
        "name": "Smith",
        "visits": [
          {
            "id": 1,
            "date": "2016-08-30 16:00:00",
            "pageViews": 18
          }
        ]
      },
      {
        "id": 2,
        "name": "Willis",
        "visits": [
          {
            "id": 2,
            "date": "2016-08-30 18:00:00",
            "pageViews": 34
          }
        ]
      }
    ]
  }
]

如果我执行类似SELECT user.name WHERE user.visits.pageViews > 20的查询,我会得到Willis

If I execute a query like SELECT user.name WHERE user.visits.pageViews > 20 I get Willis

否则,用PHP执行类似操作的最佳方法是什么?

Else, what is the best way to do something like that in PHP ?

谢谢

推荐答案

使用jq是该作业的正确工具.假设39233103.json包含在问题中的样本输入.

Use jq which is the right tool for the job. Suppose 39233103.json contains the sample input in the quesiton.

样品运行

$ jq '.[]|.user[]|select(.visits[].pageViews>20)|.name' 39233103.json
"Willis"

要获取raw output,请使用-r选项

$ jq -r '.[]|.user[]|select(.visits[].pageViews>20)|.name' 39233103.json
Willis


现在可以从php中进行操作,您可以使用 [exec] .假设以下脚本名为39233103.php


Now to do it from within php you could use [ exec ]. Suppose the below script is named 39233103.php

<?php
$output=array();
exec("jq -r '.[]|.user[]|select(.visits[].pageViews>20)|.name' 39233103.json", $output);
foreach ($output as $val){
echo $val."\n";
}
?>

输出

$ php 39233103.php
Willis


如果您不熟悉jq,请 [此] 是一个很好的起点.


If you're not familiar with jq, [ this ] is a good starting point.

这篇关于使用结构语言从json字符串中提取数据的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆