真的只会一点点 发表于 2020-12-2 12:47:56

json转换

json = [
{"id":1,"name":1,"age":1},
{"id":1,"name":2,"age":3},
{"id":1,"name":4,"age":4},
{"id":3,"name":3,"age":3},
{"id":3,"name":4,"age":5},
{"id":4,"name":12,"age":10}
]
json2 = [
{
'id': 1, 'list': [
{'name': 1, 'age': 1},
{'name': 2, 'age': 3},
{'name': 4, 'age': 4}
]
}, {
'id': 3, 'list': [
{'name': 3, 'age': 3},
{'name': 4, 'age': 5}
]
}, {
'id': 4, 'list': [
{'name': 12, 'age': 10}]
}
]
将json 转化成json2

suchocolate 发表于 2020-12-2 13:14:38

本帖最后由 suchocolate 于 2020-12-2 13:38 编辑

json库
import json

js1 = [
    {"id": 1, "name": 1, "age": 1},
    {"id": 1, "name": 2, "age": 3},
    {"id": 1, "name": 4, "age": 4},
    {"id": 3, "name": 3, "age": 3},
    {"id": 3, "name": 4, "age": 5},
    {"id": 4, "name": 12, "age": 10}
]

stream = json.dumps(js1)
data = json.loads(stream)
print(data)
print(type(data))

str替换法:js1 = [
    {"id": 1, "name": 1, "age": 1},
    {"id": 1, "name": 2, "age": 3},
    {"id": 1, "name": 4, "age": 4},
    {"id": 3, "name": 3, "age": 3},
    {"id": 3, "name": 4, "age": 5},
    {"id": 4, "name": 12, "age": 10}
]

temp = str(js1).replace('\"', '\'')
data = eval(temp)
print(data)
print(type(data))

Brick_Porter 发表于 2020-12-2 13:46:30

json = [
    {"id": 1, "name": 1, "age": 1},
    {"id": 1, "name": 2, "age": 3},
    {"id": 1, "name": 4, "age": 4},
    {"id": 3, "name": 3, "age": 3},
    {"id": 3, "name": 4, "age": 5},
    {"id": 4, "name": 12, "age": 10}
]

temp = {}
for i in json:
    id_ = i["id"]
    name = i["name"]
    age = i["age"]
    if id_ not in temp:
      temp = {'id': id_, 'list': [{'name': name, 'age': age}]}
    else:
      temp['list'].append({'name': name, 'age': age})
json2 = list(temp.values())
print(json2)

真的只会一点点 发表于 2020-12-2 23:39:05

suchocolate 发表于 2020-12-2 13:14
json库




那么,请问如何用php来实现?
php的json转换报错,谢谢

真的只会一点点 发表于 2020-12-2 23:40:47

Brick_Porter 发表于 2020-12-2 13:46


谢谢,感兴趣的话帮我想一下如何用php来实现。给点提示

suchocolate 发表于 2020-12-3 09:53:48

真的只会一点点 发表于 2020-12-2 23:39
那么,请问如何用php来实现?
php的json转换报错,谢谢

https://www.runoob.com/php/php-json.html
页: [1]
查看完整版本: json转换