PHP如何将另一个文件中的对象添加到不同JSON中的数组中

时间:2019-06-24 00:09:51

标签: php html json

我想移动该对象(在PHP中)

(json1.json)

{
    "id": "TEST",
    "name": "TEST",
    "desc": "TEST",
    "image": "TEST",
    "package": "TEST",
    "version": "1.00",
    "picpath": "TEST",
    "desc_1": "ssss",
    "desc_2": "ssss",
    "ReviewStars": "5",
    "Size": "TEST",
    "Author": "TEST",
    "apptype": "222",
    "pv": "TEST",
    "main_icon_path": "TEST",
    "main_menu_pic": "TEST",
    "releaseddate": "2019-06-19",
}

放入此数组(json2.json)

{
  "packages": [
  {
      "id": "TEST",
      "name": "TEST",
      "desc": "TEST",
      "image": "TEST",
      "package": "TEST",
      "version": "1.00",
      "picpath": "TEST",
      "desc_1": "TEST",
      "desc_2": "TEST",
      "ReviewStars": "TEST",
      "Size": "",
      "Author": "TEST",
      "apptype": "TEST",
      "pv": "TEST",
      "main_icon_path": "TEST",
      "main_menu_pic": "TEST",
      "releaseddate": "5/03/2018"
    }
    ]
}

我希望最终的json看起来像这样

{
  "packages": [
  {
      "id": "TEST",
      "name": "TEST",
      "desc": "TEST",
      "image": "TEST",
      "package": "TEST",
      "version": "1.00",
      "picpath": "TEST",
      "desc_1": "TEST",
      "desc_2": "TEST",
      "ReviewStars": "TEST",
      "Size": "",
      "Author": "TEST",
      "apptype": "TEST",
      "pv": "TEST",
      "main_icon_path": "TEST",
      "main_menu_pic": "TEST",
      "releaseddate": "5/03/2018"
    },
{
    "id": "TEST",
    "name": "TEST",
    "desc": "TEST",
    "image": "TEST",
    "package": "TEST",
    "version": "1.00",
    "picpath": "TEST",
    "desc_1": "ssss",
    "desc_2": "ssss",
    "ReviewStars": "5",
    "Size": "TEST",
    "Author": "TEST",
    "apptype": "222",
    "pv": "TEST",
    "main_icon_path": "TEST",
    "main_menu_pic": "TEST",
    "releaseddate": "2019-06-19",
}

    ]
}

iv尝试了包括该解决方案在内的许多解决方案


$datas[] = json_decode($json, true);

$datas[] = json_decode($json1, true);

$jsonData = json_encode($datas, JSON_PRETTY_PRINT | JSON_UNESCAPED_SLASHES);

file_put_contents($jpath, $jsonData);```

1 个答案:

答案 0 :(得分:0)

getchar

输出

import json
import pymysql # I am using Python 3

# string is obtained from somewhere (with extra '{' added at beginning and '}' added at end to make it valid JSON)
rec_string = '{"21283":{"count":82,"price":444},"21158":{"count":178,"price":414},"21281":{"count":157,"price":216},"21165":{"count":132,"price":858},"21284":{"count":99,"price":407},"21175":{"count":60,"price":1650},"21282":{"count":50,"price":1440},"21168":{"count":14,"price":4715},"21280":{"count":22,"price":1625}}'
# and converted to a dictionary:
rec = json.loads(rec_string)

conn = pymysql.connect(db='my_db', user='xxxxxxxx', passwd='xxxxxxxx')
cursor = conn.cursor()
for k,v in rec.items():
    cursor.execute('insert into test_table(product_id, count, value) values(%s, %s, %s)', (k, v['count'], v['price']))
conn.commit()