2024-08-16

在JavaScript中,您可以使用fetch API或XMLHttpRequest来加载JSON文件。在jQuery中,您可以使用$.getJSON方法。以下是使用这两种方法的示例代码:

使用原生JavaScript的fetch API加载JSON:




fetch('example.json')
  .then(response => response.json())
  .then(data => {
    console.log(data);
    // 处理JSON数据
  })
  .catch(error => console.error('Error fetching JSON:', error));

使用原生JavaScript的XMLHttpRequest加载JSON:




var xhr = new XMLHttpRequest();
xhr.open('GET', 'example.json', true);
xhr.onreadystatechange = function () {
  if (xhr.readyState === 4 && xhr.status === 200) {
    var json = JSON.parse(xhr.responseText);
    console.log(json);
    // 处理JSON数据
  }
};
xhr.send();

使用jQuery的$.getJSON方法加载JSON:




$.getJSON('example.json', function(data) {
  console.log(data);
  // 处理JSON数据
})
.fail(function(jqXHR, textStatus, errorThrown) {
  console.error('Error fetching JSON:', textStatus, errorThrown);
});

请确保您的服务器配置允许跨域请求(CORS),除非JSON文件与您的网站在同一个域上。

2024-08-16

以下是使用Python进行数据存储的示例代码,分别展示了将数据存储为JSON、CSV以及MySQL数据库的方法。




import json
import csv
import pymysql
 
# 示例数据
data = {
    'name': 'Alice',
    'age': 30,
    'email': 'alice@example.com'
}
 
# 存储为JSON
with open('data.json', 'w') as f:
    json.dump(data, f)
 
# 存储为CSV
with open('data.csv', 'w', newline='') as f:
    writer = csv.DictWriter(f, fieldnames=data.keys())
    writer.writeheader()
    writer.writerow(data)
 
# 存储到MySQL数据库
# 假设数据库已经创建,并且有一个表结构如下:
# CREATE TABLE users (name VARCHAR(100), age INT, email VARCHAR(100));
 
# 连接到数据库
connection = pymysql.connect(host='localhost', user='your_username', password='your_password', db='your_database')
 
try:
    # 使用cursor()方法获取操作游标 
    with connection.cursor() as cursor:
        # SQL 插入语句
        sql = "INSERT INTO users (name, age, email) VALUES (%s, %s, %s)"
        cursor.execute(sql, (data['name'], data['age'], data['email']))
        
    # 提交到数据库执行
    connection.commit()
    
except pymysql.MySQLError as e:
    print(e)
finally:
    connection.close()

这段代码展示了如何将数据以不同的格式存储到文件和数据库中。在实际应用中,你需要根据你的具体需求来调整数据库的连接参数和SQL语句。

2024-08-16



uses
  System.JSON;
 
procedure ParseJSONExample;
var
  JSONData: TJSONValue;
  JSONObject: TJSONObject;
  JSONArray: TJSONArray;
  Item: TJSONValue;
  NameValue: TJSONValue;
begin
  // 假设有一段 JSON 字符串
  const JSONString = '{"employees":[' +
                      '{"firstName":"John","lastName":"Doe" },' +
                      '{"firstName":"Anna","lastName":"Smith" },' +
                      '{"firstName":"Peter","lastName":"Jones" }]}'
  ;
 
  // 解析 JSON 字符串
  JSONData := TJSONObject.ParseJSONValue(JSONString);
  try
    // 确保 JSON 数据被正确解析
    if JSONData <> nil then
    begin
      // 获取 "employees" 数组
      JSONArray := JSONData.GetValue<TJSONArray>('employees');
      // 遍历数组
      for Item in JSONArray do
      begin
        // 将每个数组元素转换为 JSON 对象
        JSONObject := Item as TJSONObject;
        // 获取对象中的 "firstName" 和 "lastName" 值
        NameValue := JSONObject.GetValue('firstName');
        Writeln('FirstName: ', NameValue.Value);
        NameValue := JSONObject.GetValue('lastName');
        Writeln('LastName: ', NameValue.Value);
      end;
    end
    else
      Writeln('JSON is not valid');
  finally
    // 释放 JSON 数据对象
    JSONData.Free;
  end;
end;

这段代码展示了如何使用 Delphi 中封装好的 JSON 解析库来解析一个简单的 JSON 字符串。首先,使用 TJSONObject.ParseJSONValue 方法解析 JSON 字符串,然后检查解析结果是否为 nil,并对解析到的数据进行处理。最后,确保释放所有使用的资源。

2024-08-16

在Python中,你可以使用json模块来将字符串(str)与JSON数据相互转换。

将字典转换为JSON字符串:




import json
 
data = {
    "name": "John",
    "age": 30,
    "city": "New York"
}
 
json_string = json.dumps(data)
print(json_string)  # 输出: {"name": "John", "age": 30, "city": "New York"}

将JSON字符串转换为字典:




import json
 
json_string = '{"name": "John", "age": 30, "city": "New York"}'
 
data = json.loads(json_string)
print(data)  # 输出: {'name': 'John', 'age': 30, 'city': 'New York'}

这是最常见的转换方式,但json.dumpsjson.loads还有其他选项,例如处理中文字符的选项等。

2024-08-16



# 导入必要的模块
import json
import joblib
import pickle
 
# 假设有一个字典变量
data_dict = {
    'name': 'Alice',
    'age': 30,
    'location': 'Wonderland'
}
 
# 将变量保存到txt文件
with open('data.txt', 'w') as file:
    file.write(str(data_dict))
 
# 从txt文件中加载变量
with open('data.txt', 'r') as file:
    data_loaded_from_txt = eval(file.read())
 
# 将变量保存到json文件
with open('data.json', 'w') as file:
    json.dump(data_dict, file)
 
# 从json文件中加载变量
with open('data.json', 'r') as file:
    data_loaded_from_json = json.load(file)
 
# 将变量保存到pickle文件
with open('data.pkl', 'wb') as file:
    pickle.dump(data_dict, file)
 
# 从pickle文件中加载变量
with open('data.pkl', 'rb') as file:
    data_loaded_from_pickle = pickle.load(file)
 
# 将变量保存到joblib文件
import numpy as np
from joblib import dump, load
data_array = np.arange(10)
dump(data_array, 'data.joblib')
 
# 从joblib文件中加载变量
data_loaded_from_joblib = load('data.joblib')
 
# 打印加载后的变量
print(data_loaded_from_txt)
print(data_loaded_from_json)
print(data_loaded_from_pickle)
print(data_loaded_from_joblib)

这段代码展示了如何使用不同的格式来保存和加载Python变量。txt文件通过writeread方法保存和读取Python对象的字符串表示;json文件使用json模块的dumpload方法来保存和读取JSON格式的数据;pickle文件使用pickle模块的dumpload方法来保存和读取Python对象的二进制表示;joblib文件使用joblib库的dumpload方法来保存和读取NumPy数组。这些方法都可以用于不同类型的数据和变量。

2024-08-16



#!/bin/bash
 
# 定义taskPHP项目路径
TASKPHP_PATH='/www/wwwroot/taskphp'
 
# 定义taskPHP的入口文件
ENTRYPOINT='/www/wwwroot/taskphp/start.php'
 
# 定义json配置文件路径
JSON_CONFIG_PATH='/www/wwwroot/taskphp/config/crontab.json'
 
# 定义PHP执行程序
PHP_BIN='/www/server/php/72/bin/php'
 
# 使用PHP执行taskPHP的入口文件,并传递json配置文件作为参数
$PHP_BIN $ENTRYPOINT $JSON_CONFIG_PATH

这段代码是一个简单的bash脚本,用于在宝塔面板中设置定时任务来运行taskPHP应用。脚本中定义了taskPHP项目的路径、入口文件的路径、json配置文件的路径和PHP执行程序的路径。然后使用PHP执行taskPHP的入口文件,并将json配置文件作为参数传递。这样,你就可以通过宝塔面板的定时任务功能来按照这个bash脚本设定的时间执行taskPHP应用了。

2024-08-16



import org.gdal.ogr.DataSource;
import org.gdal.ogr.Driver;
import org.gdal.ogr.Feature;
import org.gdal.ogr.FeatureDefn;
import org.gdal.ogr.FieldDefn;
import org.gdal.ogr.Geometry;
import org.gdal.ogr.Layer;
import org.gdal.ogr.ogr;
 
public class GeoJSONReadAndWrite {
 
    public static void main(String[] args) {
        // 初始化GDAL库
        ogr.RegisterAll();
 
        // 创建GeoJSON数据源
        String geoJsonFile = "path/to/your/geojsonfile.geojson";
        DataSource ds = ogr.Open(geoJsonFile, 0);
        if (ds == null) {
            System.out.println("打开GeoJSON文件失败");
            return;
        }
 
        // 获取层
        Layer layer = ds.GetLayerByIndex(0);
        if (layer == null) {
            System.out.println("获取层失败");
            return;
        }
 
        // 创建新的数据源
        String dbFile = "path/to/your/databasefile.gpkg";
        Driver dbDriver = ogr.GetDriverByName("GPKG");
        if (dbDriver == null) {
            System.out.println("获取数据库驱动失败");
            return;
        }
 
        // 创建数据源
        DataSource dbDs = dbDriver.CreateDataSource(dbFile);
        if (dbDs == null) {
            System.out.println("创建数据源失败");
            return;
        }
 
        // 创建图层
        FeatureDefn featureDefn = layer.GetLayerDefn();
        String layerName = "new_layer";
        Layer dbLayer = dbDs.CreateLayer(layerName, featureDefn.GetGeomFieldDefn(0), ogr.wkbNone);
        if (dbLayer == null) {
            System.out.println("创建图层失败");
            return;
        }
 
        // 复制字段
        for (int i = 0; i < featureDefn.GetFieldCount(); i++) {
            FieldDefn fieldDefn = featureDefn.GetFieldDefn(i);
            dbLayer.CreateField(fieldDefn);
        }
 
        // 复制几何字段
        dbLayer.CreateGeomField(new Geometry(ogr.wkbMultiPolygon));
 
        // 复制要素
        Feature feature;
        while ((feature = layer.GetNextFeature()) != null) {
            Feature newFeature = dbLayer.CreateFeature(feature.Clone());
            newFeature.SetFID(feature.GetFID());
            dbLayer.SetFeature(newFeature);
            newFeature.Destroy();
            feature.Destroy();
        }
 
        // 关闭数据源
        dbLayer.SyncToDisk();
        dbLayer = null;
        dbDs.Destroy();
        layer = null;
        ds = null;
 
        System.out.println("GeoJSON数据成功
2024-08-16

在MySQL中,你可以使用JSON_EXTRACT函数来处理JSON字符串。这个函数可以从一个JSON文档中提取指定的值。

假设我们有一个名为users的表,它有一个名为user_info的列,该列包含JSON数据。




CREATE TABLE users (
    id INT AUTO_INCREMENT PRIMARY KEY,
    user_info JSON
);

你可以插入一些包含JSON的数据:




INSERT INTO users (user_info) VALUES ('{"name": "John", "age": 30, "city": "New York"}');
INSERT INTO users (user_info) VALUES ('{"name": "Anne", "age": 25, "city": "Chicago"}');

如果你想要提取所有用户的名字,你可以使用JSON_EXTRACT




SELECT JSON_EXTRACT(user_info, '$.name') AS user_name FROM users;

如果你想要提取所有年龄大于24岁的用户,你可以使用JSON_UNQUOTEJSON_EXTRACT




SELECT JSON_UNQUOTE(JSON_EXTRACT(user_info, '$.age')) AS user_age FROM users WHERE JSON_UNQUOTE(JSON_EXTRACT(user_info, '$.age')) > 24;

JSON_UNQUOTE函数用于去除JSON提取结果的引号。

以上代码假定你已经有了一个运行中的MySQL服务器,并且你已经连接到了你想要操作的数据库。

2024-08-16

在Spring Boot中处理MySQL中JSON类型字段,你可以使用@Type注解来指定字段的自定义类型处理器。以下是一个使用Jackson库来处理JSON字段的例子:

首先,添加依赖到你的pom.xml




<dependency>
    <groupId>com.vladmihalcea</groupId>
    <artifactId>hibernate-types-json</artifactId>
    <version>2.10.2</version>
</dependency>

然后,在你的实体类中使用@Type注解来指定JSON字段的类型:




import com.vladmihalcea.hibernate.type.json.JsonBinaryType;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.hibernate.annotations.Type;
import org.hibernate.annotations.TypeDef;
 
import javax.persistence.Entity;
import javax.persistence.Id;
import javax.persistence.Table;
import java.util.Map;
 
@Entity
@Table(name = "your_table")
@TypeDef(name = "jsonb", typeClass = JsonBinaryType.class)
public class YourEntity {
 
    @Id
    private Long id;
 
    @Type(type = "jsonb")
    private Map<String, Object> jsonData;
 
    // Getters and setters...
}

确保你的ObjectMapper配置正确,并且你的实体类中的jsonData字段使用了Map来存储JSON对象。

最后,确保在你的application.propertiesapplication.yml中配置了Hibernate类型:




# application.properties
spring.jpa.properties.hibernate.types_to_string_mapping_enabled=true

这样就可以在Spring Boot应用中正确地存储和读取MySQL中的JSON类型字段了。

2024-08-16

JSON_TABLE 是 MySQL 8.0 引入的一个函数,它可以将 JSON 数据转换为临时的表格式表示,然后可以像查询普通表一样查询这些数据。

下面是一个简单的例子,假设我们有一个包含 JSON 数据的列 json_colorders 表中:




SELECT 
    order_id, 
    data.order_date, 
    data.customer_id
FROM 
    orders, 
    JSON_TABLE(
        json_col, 
        '$' COLUMNS (
            order_date DATE PATH '$.orderDate',
            customer_id INT PATH '$.customerId'
        )
    ) AS data;

在这个例子中,orders 表中的每条记录都会被扩展,以显示嵌套在 json_col 中的 orderDatecustomerId 的值。COLUMNS 关键字后面定义了我们想要从 JSON 中提取的数据以及它们对应的路径和数据类型。

这个函数使得处理 JSON 数据变得更加方便和灵活,可以用于查询、分析和转换 JSON 数据。